首先定义一个Student类作为初始数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqSpace
{
public class Student
{
public int Age { get; set; }
public string Name { get; set; }
}
public class Data
{
public static List<Student> StuList = new List<Student>()
{
new Student()
{
Name = "张三",
Age = 12
},
new Student()
{
Name = "王五",
Age = 28
},
new Student()
{
Name = "李四",
Age = 21
},
new Student()
{
Name = "赵六",
Age = 33
},
};
}
}
再实现所有的逻辑
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqSpace
{
public class LinqTest
{
public static void Show()
{
//查找列表中年龄大于26的学生
///方法一:直接遍历
List<Student> oldList = new List<Student>();
foreach(Student stu in Data.StuList)
{
if (stu.Age > 26)
{
oldList.Add(stu);
}
}
foreach(Student st in oldList)
{
Console.WriteLine("name={0},age={1}", st.Name, st.Age);
}
///方法二:使用linq
var linq = from s in Data.StuList
where s.Age > 26
select s;
foreach (Student st in linq)
{
Console.WriteLine("name={0},age={1}", st.Name, st.Age);
}
///方法三:使用lambda
var lambda = Data.StuList.Where(s => s.Age > 26);
//实际上该表达式原型是:
var lambda1 = Enumerable.Where<Student>(Data.StuList, s => s.Age > 26);//由于这个where函数的第一个形参是this类型的,
//所以可以直接用第一个形参来调用这个where
foreach (Student st in lambda)
{
Console.WriteLine("name={0},age={1}", st.Name, st.Age);
}
///自己实现Enumerable的where例子
var lambdaExt = Data.StuList.WhereMy<Student>(s => s.Age > 26);
foreach (Student st in lambdaExt)
{
Console.WriteLine("name={0},age={1}", st.Name, st.Age);
}
}
}
public static class LinqExtend
{
public static IEnumerable<T> WhereMy<T>(this IEnumerable<T> tList, Func<T, bool> func) //where T : Student //约束一下T
{
var linq = from s in tList
//where s.Age>26
where func(s)
select s;
return linq;
}
}
}