SQLServer商业智能系列:MDX基础
【IT168技术文档】
Where 子句的用法
我们除了可以如下方式书写带Where子句的LINQ外:
还可以对数组(所有实现了IEnumerable接口的对象都可以)的实体使用 Where 扩展方法。from p in products where p.UnitsInStock > 0 && p.UnitPrice > 3.00M select p;
把一个查询语句写成多个扩展函数的方式,这其实是编译器处理查询语句的方法,比如下面的查询语句:
编译器在编译后,替我们产生的代码等价于如下的代码:int[] arr = new int[] { 8, 5, 89, 3, 56, 4, 1, 58 }; var m = from n in arr where n < 5 orderby n select n;
下面我们来看一个使用Where扩展方法的例子:IOrderedSequence m = arr.Where(delegate (int n) { return (n < 5); }).OrderBy(delegate (int n) { return n; });
我们有一个字符串数组,一次是0到9的英文单词,我们查询出这10个字符的长度比它所在数组的位置 这两个数字比较小的英文单词.
这个查询可能有些绕口,你可以先看下面这些代码:
输出结果:public static void LinqDemo01() { string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var shortDigits = digits.Where((dd, aa) => dd.Length < aa); Console.WriteLine("Short digits:"); foreach (var d in shortDigits) Console.WriteLine("The word {0} is shorter than its value.", d); }
下面我们就来分析上述代码中最核心的代码:Short digits: The word five is shorter than its value. The word six is shorter than its value. The word seven is shorter than its value. The word eight is shorter than its value. The word nine is shorter than its value.
这行代码都赶了些什么?digits.Where((dd, aa) => dd.Length < aa);
1、Where子句其实是用扩展方法来实现的
微软替我们实现的 Where 子句对应的扩展函数实际是如下的定义:
namespace System.Linq { public delegate TResult Func(TArg0 arg0, TArg1 arg1); public static class Enumerable { public static IEnumerable Where(this IEnumerable source, Func predicate); public static IEnumerable Where(this IEnumerable source, Func predicate); } }
0
相关文章