LINQ 步步学-LINQ to Object(1)

作者:vkvi 来源:ITPOW(原创) 日期:2009-8-20

查询数组

int[] arr = new int[] {5, 1, 9, 3, 4, 0, 8 };
var m = from item in arr
        select item;
foreach (var item in m)
{
    Response.Write(item.ToString() + "<br>");
}

结果:

5
1
9
3
4
0
8

可以看出 LINQ 和 SQL 很像,两点不同:

  • select 在后面,这可能是受某些限制,只好把 select 放在后面。
  • from 与数据之间多了个“变量名 in”。

查询 List

System.Collections.Generic.List<int> arr = new System.Collections.Generic.List<int> { 5, 1, 9, 3, 4, 0, 8 };
var m = from item in arr
        select item;
foreach (var item in m)
{
    Response.Write(item.ToString() + "<br>");
}

可以看出查询 List 与查询数组完全是一样的。另请参见 C# 3.0 -集合初始化设置

查询 Dictionary

System.Collections.Generic.Dictionary<int, int> arr = new System.Collections.Generic.Dictionary<int, int>();
arr.Add(0, 5);
arr.Add(1, 1);
arr.Add(2, 9);
arr.Add(3, 3);
arr.Add(4, 4);
arr.Add(5, 0);
arr.Add(6, 8);
var m = from item in arr
        select item;
foreach (var item in m)
{
    Response.Write(item.Value.ToString() + "<br>");
}

我们可以发现在查询 Dictionary 时,查询语句是一样的,但输出时,不再是 item.ToString(),而是 item.Value.ToString(),并且我们在写完“item.”后,“Value”会自动出现 IntelliSense 中,不需要我们记忆。

所以说查询出来的可以是普通类型的值,也可以是对象。

如果没有结果,怎么判断?

不是用 null 来判断,而是用 .Count() 来判断。

相关阅读

相关文章