直接上代碼:
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