Linq

IEnumerable

IEnumerable:可枚举类型,一个方法GetEnumerato(),实现该接口的类就可以对它进行遍历。
IEnumerator:枚举器,一个属性Current,两个方法MoveNext(),Reset()。

扩展方法

在不改变源码的基础上为类添加新的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
namespace LinqTest
{
public class Caculate
{
public int Add(int num1,int num2)
{
return num1 + num2;
}
}

// 拓展Caculate类
public static class CaculateExt
{
public static int AddExt(this Caculate caculate,int num1, int num2,int num3)
{
return num1 + num2 + num3;
}
}

class Program
{
static void Main(string[] args)
{
Caculate caculate = new Caculate();
int num1 = caculate.Add(1, 1);
int num2 = caculate.AddExt(1, 1, 1);
Console.WriteLine(num1);// 2
Console.WriteLine(num2);// 3
}
}
}

Linq

  • linq to object 查询内存中的数据
  • linq to sql 查询数据库中的数据
  • linq to xml 查询xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 原始数据
List<Student> studentList = new List<Student>()
{
new Student(){Id=001,Name="张三",Age=21,ClassId=1},
new Student(){Id=002,Name="李四",Age=18,ClassId=1},
new Student(){Id=003,Name="王五",Age=24,ClassId=2},
new Student(){Id=004,Name="赵六",Age=16,ClassId=3},
new Student(){Id=005,Name="陈小",Age=22,ClassId=3},
new Student(){Id=006,Name="刘麻子",Age=28,ClassId=1}
};
List<StuClass> stuClasses = new List<StuClass>()
{
new StuClass(){Id=1,ClassName="计科1班"},
new StuClass(){Id=2,ClassName="计科2班"},
new StuClass(){Id=3,ClassName="计科3班"}
};

Where 指定条件查询数据

1
List<Student> students1 = studentList.Where(stu => stu.Age > 18).ToList();

ForEach 遍历数据

1
students1.ForEach(stu => Console.WriteLine(stu));

Select 投影 将原始类(一般为po)的属性投影到新的类(一般为dto)的属性中

1
var studentsWithIdAndName = studentList.Select(stu => new {Id=stu.Id,Name=stu.Name}).ToList();

Join 内连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var studentsWithClass = studentList.Join(stuClasses,stu=>stu.ClassId,clazz =>clazz.Id,
(stu,clazz)=>new StudentWithClass()
{
Id=stu.Id,
Name=stu.Name,
Age=stu.Age,
ClassId=stu.ClassId,
ClassName=clazz.ClassName
}).ToList();

// 表达式写法 用于处理大于2个list的连接查询
var studentsWithClass2 = (from s in studentList join c in stuClasses on s.ClassId equals c.Id
select new StudentWithClass()
{
Id = s.Id,
Name = s.Name,
Age = s.Age,
ClassId = s.ClassId,
ClassName = c.ClassName
}).ToList();

Take 获取指定数量的数据

Skip 跳过指定数量的数据

OrderBy 根据指定元素升序排列

OrderByDescending 根据指定元素降序排列

Where + Contains 模糊查询

1
var students2 = studentList.Where(stu => stu.Name.Contains("张")).OrderByDescending(stu => stu.Age).ToList();

GroupBy 指定属性进行分组

1
2
3
4
5
6
7
8
9
10
IEnumerable<IGrouping<int,Student>> items = studentList.GroupBy(s => s.Age);
foreach(IGrouping<int,Student> studentByAge in items)
{
Console.WriteLine(studentByAge.Key);
foreach(Student s in studentByAge)
{
Console.WriteLine(s);
}
Console.WriteLine("*************");
}