LinQ Where接收一个有返回值为bool的委托。
List<Student> list = new List<Student>();
var res = list.Where(x=>x.Age>0)
模拟LinQ Where
Extend.cs
public static class Extends{
//其实就是循环遍历集合的每个对象,if(bool)
public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> func) where T : class
{
foreach (var item in source)
{
if (func.Invoke(item))
yield return item;
}
}
}
用带有返回值的委托来代替 不同的 if 。
相当于把 if(item.age>20) / if(item.Name==“XX”) 抽取出来用 lambda表达式来写。
Progran.cs
static void Main(){
List<Student> list = new List<Student>();
list.Add();
...
var res = list.Where(x=>x.Age>20);
}