首页 > Python基础教程 >
-
C#教程之c# Enumerable中Aggregate和Join的使用
The Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>) method makes it simple to perform a calculation over a sequence of values. This method works by calling func one time for each element in source. Each time func is called, Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>) passes both the element from the sequence and an aggregated value (as the first argument to func). The first element of source is used as the initial aggregate value. The result of func replaces the previous aggregated value. Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>) returns the final result of func.
To simplify common aggregation operations, the standard query operators also include a general purpose count method, Count, and four numeric aggregation methods, namely Min, Max, Sum, and Average.
直接上代码:
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而已。
===================
A join refers to the operation of correlating the elements of two sources of information based on a common key. Join brings the two information sources and the keys by which they are matched together in one method call
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个参数。