SQLServer商业智能系列:MDX基础
其中红色字体的那个扩展函数,就是我们上面代码实际使用的扩展函数。
我们这个扩展函数参数:Func predicate 的定义看上面代码的绿色delegate 代码。
2、Where 子句参数书写的是Lambda 表达式
LINQ中所有关键字比如 Select,SelectMany, Count, All 等等其实都是用扩展方法来实现的。上面的用法同样也适用于这些关键字子句。
3、这个Where子句中Lambda 表达式第二个参数是数组索引,我们可以在Lambda 表达式内部使用数组索引。来做一些复杂的判断。
具有数组索引的LINQ关键字除了Where还以下几个Select,SelectMany, Count, All
我们下面就来依次举例
Select 子句使用数组索引的例子
下面代码有一个整数数组,我们找出这个数字是否跟他在这个数组的位置一样
输出结果:public static void LinqDemo01() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) }); Console.WriteLine("Number: In-place?"); foreach (var n in numsInPlace) Console.WriteLine("{0}: {1}", n.Num, n.InPlace); }
Number: In-place?
5: False
4: False
1: False
3: True
9: False
8: False
6: True
7: True
2: False
0: False
其中我们用到的这个Select子句对应的扩展函数定义,以及其中Func委托定义如下:
SelectMany 子句使用数组索引的例子public static IEnumerableSelect(this IEnumerable source, Func selector); public delegate TResult Func(TArg0 arg0, TArg1 arg1);
几个句子组成的数组,我们希望把这几个句子拆分成单词,并显示每个单词在那个句子中。查询语句如下:
结果:public static void Demo01() { string[] text = { "Albert was here", "Burke slept late", "Connor is happy" }; var tt = text.SelectMany((s, index) => from ss in s.Split(' ') select new { Word = ss, Index = index }); foreach (var n in tt) Console.WriteLine("{0}:{1}", n.Word,n.Index); }
Albert:0
was:0
here:0
Burke:1
slept:1
late:1
Connor:2
is:2
happy:2
SkipWhile 子句使用数组索引的例子
SkipWhile 意思是一直跳过数据,一直到满足表达式的项时,才开始返回数据,而不管之后的项是否仍然满足表达式,需要注意他跟Where是不一样的,Where是满足条件的记录才返回,SkipWhile 是找到一个满足条件的,然后后面的数据全部返回。
下面例子返回一个整数数组中,这个整数比他自身在这个数组的位置大于等于的第一个位置以及之后的数据。
public static void Linq27() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var laterNumbers = numbers.SkipWhile((n, index) => n >= index); Console.WriteLine("All elements starting from first element less than its position:"); foreach (var n in laterNumbers) Console.WriteLine(n); }
0
相关文章