http://topic.csdn.net/u/20090304/17/75f53736-30cf-47ad-9c78-8c378646fea8.html
Linq中查询二维数组收藏
<script type="text/javascript"> document.body.oncopy = function() { if (window.clipboardData) { setTimeout(function() { var text = clipboardData.getData("text"); if (text && text.length>300) { text = text + "/r/n/n本文来自CSDN博客,转载请标明出处:" + location.href; clipboardData.setData("text", text); } }, 100); } } </script> <script>function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}</script> 以下代码为在一个4*4的二维int数组中将大于5的元素查出:
- static void Main( string [] args)
- {
- int [,] array = new int [4, 4];
- for ( int i = 0; i < 4; i++)
- for ( int j = 0; j < 4; j++)
- array[i, j] = (i + 1) * (j + 1);
- var intQuery = from i in array.Cast< int >()
- where i > 5
- select i;
- foreach ( int i in intQuery)
- Console.WriteLine(i);
- }
由于二维数组无法直接转换为IEnumerable<T>类型,所以,通过其Cast<T>()方法先将其转换为IEnumerable<T>再进行查询
Enumerable. Cast< TResult > () 泛型方法 将 IEnumerable 的元素转换为指定的类型。
此方法通过使用延迟执行实现。即时返回值为一个对象,该对象存储执行操作所需的所有信息。只有通过直接调用对象的 GetEnumerator 方法或使用 Visual C# 中的 foreach (或 Visual Basic 中的 For Each )来枚举该对象时,才执行此方法表示的查询。
Cast< TResult>() (IEnumerable) 方法通过提供必要的类型信息,可在非泛型集合上调用标准查询运算符。例如,ArrayList 并不实现 IEnumerable< T> ( ) ,但通过调用 ArrayList 对象上的 Cast< TResult> ( ) (IEnumerable) ,就可以使用标准查询运算符查询该序列。
如果元素无法强制转换为 TResult 类型,则此方法将引发异常。若要只获取可以强制转换为 TResult 类型的元素,请使用 OfType< TResult> () 方法,而不是 Cast< TResult> ( ) (IEnumerable) 。
在查询表达式中,显式类型迭代变量会转换为 Cast< TResult> ( ) (IEnumerable) 的一个调用。