Welcome

首页 / 软件开发 / C# / c# Enumerable中Aggregate和Join的使用

c# Enumerable中Aggregate和Join的使用2017-01-07直接上代码:

IEnumerable<int> list = Enumerable.Range(2, 10);int all = list.Aggregate((sum, index) => sum + index);
调试, 第一次调用,发现sum和index分别取列表的第1和第2个值:

F5下一步,发现把index加到sum了 (sum += index), 然后index取下一个值, 并累积到sum,重复此步骤直到取完列表中的值:

最后计算结果是65

另外2个重载函数:

int all = list.Aggregate(10, (sum, index) => sum + index);
第2个参数与上一个例子参数一样,累积列表中值,第1个参数是初始值, 会应用到累积值,在这里相当于用10加65,计算结果75。

bool is75 = list.Aggregate(10, (sum, index) => sum + index, res => res == 75);
第1第2个参数同上,第3个参数是对累积结果做判断,在这个例子里判断累积结果是否等于75,计算结果是true。

从中可以发现,list.Aggregate((sum, index) => sum + index)其实是list.Aggregate(0, (sum, index) => sum + index)的特例,相当于初始值为0而已。

===================

Join使用,看代码

Persion结构:

public struct Persion{public int index;public string name;public Persion(int index, string nm){this.index = index;name = nm;}}
Pet结构:

public struct Pet{public string name;public Persion owner;public Pet(string name, Persion person){this.name = name;owner = person;}}
Persion_Pet结构:

public struct Persion_Pet{public string persionName;public string petName;public Persion_Pet(string persion, string pet){persionName = persion;petName = pet;}}
Join使用:

Persion p1 = new Persion(1, "张三");Persion p2 = new Persion(2, "李四");Persion p3 = new Persion(3, "路人甲");List<Persion> people = new List<Persion>() { p1, p2, p3 };Persion p4 = new Persion(4, "路人乙");Pet dog = new Pet("欢欢", p1);Pet cat = new Pet("咪咪", p2);Pet cat2 = new Pet("cat2", p4);List<Pet> petList = new List<Pet>() { dog, cat, cat2 };var res = people.Join(petList, persion => persion, pet => pet.owner, (persion, pet) => new Persion_Pet(persion.name, pet.name)).ToList();
结果:

关键在于join会比较第2个参数与第3个参数的返回值,只有相等时才会继续第4个参数。

来源:http://www.cnblogs.com/gujf2016/p/6255577.html