where子句非常简单,它的语法跟SQL的语法很像,但是有几点需要注意的:
1) 判断相等应该用”==”而不是”=”
2) 逻辑与应该用”&&” 而不是and
3) 逻辑或应该用”||”而不是or
4) 一个查询表达式可以包含多个where条件
5) where 子句除了第一句和最后一句外,可以出现在查询表达式的任何地方
where子句非常简单,我们看2个例子就好。
int [] nums = new int[]{4,6,7,1,0,23,5,9,12}; var evenNums = from num in nums where num%2 == 0 && num < 10 select num; foreach (var evenNum in evenNums) { Console.WriteLine(evenNum); }
这个例子就是从一个数组里面找出小于10的所有偶数。
where子句中也可以引用方法,只要该方法返回bool值
private static bool IsEven(int num) { return num%2 == 0; } private static void WhereClause() { int [] nums = new int[]{4,6,7,1,0,23,5,9,12}; var evenNums = from num in nums where IsEven(num) select num; foreach (var evenNum in evenNums) { Console.WriteLine(evenNum); } }
其中IsEven为一个返回bool值的方法。
参考:webcast 《跟我一起学Visual Studio 2008系列课程》