LINQ学习笔记(8) 标准查询运算符(下)

  接着上午的总讲,下午要总结的是标准查询运算符(下)的内容。主要的内容是委托作为标准查询运算符的参数的相关知识。

首先我们要知道把泛型委托作为参数的作用是什么?泛型委托用于给运算符提供用户自定义的代码。

LINQ预定义的委托类型:

LINQ定义了一套5种泛型委托类型与标准查询运算符一起使用。它们就是Func委托。如下代码所示:

public delegate TR Func<TR>();//第1种,没有参数。
public delegate TR Func<T1, TR>(T1 a1);//第2种,接受一个参数,其中TR代表返回值。
public delegate TR`Func<T1,T2,TR>(T1 a1,T2 a2);//第3种,接受两个参数。
public delegate TR`Func<T1,T2,T3,TR>(T1 a1,T2 a2,T3 a3);//第4种,接受三个参数。
public delegate TR`Func<T1,T2,T3,T4,TR>(T1 a1,T2 a2,T3 a3,T4 a4);//第5种,接受四个参数。

另外,我们需要注意的是:

1,我们用作实参的委托对象必须是这5种类型之一。

2,TR代表返回值,并且总是在类型参数列表中的最后一个。

了解了这些,我们回头再来看一下Count的声明,我们可以发现第二个参数必须是委托对象,它接受单个T类型的参数作为方法参数并且返回一个bool类型的值。如:

public static int Count<T>(this IEnumerable<T> source,Func<T,bool> predicate);//其中T表示参数类型,bool表示返回类型。

使用Func委托:

我们已经对Count运算符的签名和LINQ中泛型委托参数有了初步的了解,下面我们通过一个示例来更深入地理解泛型委托在标准查询运算符中的应用了。

 1 class Program
2 {
3 static bool IsOdd(int x)//创建泛型委托对象使用的方法
4 {

5 return x % 2 == 1;
6 }
7 static void Main(string[] args)
8 {
9 int[] intArray = { 3,4,5,6,7,9};
10
11 Func<int, bool> myDel = new Func<int, bool>(IsOdd);//创建泛型委托对象,并用IsOdd()方法来初始化它。
12 var countOdd = intArray.Count(myDel);//使用委托。
13

14 Console.WriteLine("Count of odd numbers:{0}",countOdd);
15 Console.ReadKey();
16 }
17 /*
18 程序输出:Count of odd numbers:4
19 */

20 }

使用匿名方法来简化代码:

代码如下:

 1 class Program
2 {
3 static void Main(string[] args)
4 {
5 int[] intArray = { 3,4,5,6,7,9};
6
7 Func<int, bool> myDel = delegate(int x)//使用匿名方法简写
8 {

9 return x % 2 == 1;
10 };
11 var countOdd = intArray.Count(myDel);//使用委托。
12

13 Console.WriteLine("Count of odd numbers:{0}",countOdd);
14 Console.ReadKey();
15 }
16 /*
17 程序输出:Count of odd numbers:4
18 */

19 }

使用lambda表达式继续简化代码:

我们可以继续使用lambda表达式来代替匿名方法来简化代码,如下:

 1 class Program
2 {
3 static void Main(string[] args)
4 {
5 int[] intArray = { 3,4,5,6,7,9};
6
7 var countOdd = intArray.Count(x=>x%2==1);//使用lambda表达式
8

9 Console.WriteLine("Count of odd numbers:{0}",countOdd);
10 Console.ReadKey();
11 }
12 /*
13 程序输出:Count of odd numbers:4
14 */

15 }

使用lambda表达式也是我们在实际中最常使用的方式,所以必须得非常熟练。至此,LINQ查询的预备知识差不多学习完了,从下一篇开始学习LINQ查询的实际使用,希望大家继续关注,谢谢!

原文地址:https://www.cnblogs.com/mcgrady/p/2311026.html