码迷,mamicode.com
首页 > Windows程序 > 详细

c#-LinQ

时间:2016-04-27 22:22:29      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:

参考30分钟学习LinQ:

http://www.cnblogs.com/liulun/archive/2013/02/26/2909985.html 

 

三种泛型委托:

//Predicate 1,Bool类型返回值;   2,只有1个参数
var wt1 = new Predicate<int>(More);
//Action  1,没有返回值;    2,多个参数
var wt2 = new Action<int, string>(VoidMethod);
//Func   1,最后一个是返回值    2,多个参数
var wt3 = new Func<int, string, string>(StringMethod);

解释一下Lambda表达式:

//Lambda表达式
List<int> arr = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
arr.ForEach(new Action<int>(delegate (int a) { Console.WriteLine(a); }));
arr.ForEach(new Action<int>(a => Console.WriteLine(a)));

//这里解释一下这个lambda表达式
//< 1 >  a是输入参数,编译器可以自动推断出它是什么类型的,
//如果没有输入参数,可以写成这样:() => Console.WriteLine("ddd")
//< 2 > =>是lambda操作符
//< 3 >  Console.WriteLine(a)是要执行的语句。如果是多条语句的话,可以用{ }包起来。如果需要返回值的话,可以直接写return语句

最后是Linq,两个常用的查询操作符:

Where条件过滤,Select条件投影

Where:需要传一个Func(type,bool)的泛型委托,下面的例子是List<int>,所以type = int。Select也是如此。

 

****Select****
//每个元素+1
List<int> aa = new List<int>() { 1, 2, 3, 4 };
IEnumerable<int> aaNew = aa.Select<int, int>(a => a + 1);
//每个元素前面加个Weather
List<string> ss = new List<string>() { "Ice", "Fire", "Wind", "Snow" };
IEnumerable<string> ssNew = ss.Select<string, string>(v => "Weather" + v);

****Where****
//过滤出a>3的元素
List<int> arr = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
var a = arr.Where(a => { return a > 3; });

 

c#-LinQ

标签:

原文地址:http://www.cnblogs.com/kykstyle/p/5440356.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!