c# Enumerable中Aggregate和Join的運用。本站提示廣大學習愛好者:(c# Enumerable中Aggregate和Join的運用)文章只能為提供參考,不一定能成為您想要的結果。以下是c# Enumerable中Aggregate和Join的運用正文
參考頁面:
http://www.yuanjiaocheng.net/entity/entitytypes.html
http://www.yuanjiaocheng.net/entity/entity-relations.html
http://www.yuanjiaocheng.net/entity/entity-lifecycle.html
http://www.yuanjiaocheng.net/entity/code-first.html
http://www.yuanjiaocheng.net/CSharp/csharprumenshili.html
直接上代碼:
IEnumerable<int> list = Enumerable.Range(2, 10); int all = list.Aggregate((sum, index) => sum + index);View Code
調試, 第一次調用,發現sum和index辨別取列表的第1和第2個值:
F5下一步,發現把index加到sum了 (sum += index), 然後index取下一個值, 並累積到sum,反復此步驟直到取完列表中的值:
最後計算後果是65
另外2個重載函數:
int all = list.Aggregate(10, (sum, index) => sum + index);View Code
第2個參數與上一個例子參數一樣,累積列表中值,第1個參數是初始值, 會使用到累積值,在這裡相當於用10加65,計算後果75。
bool is75 = list.Aggregate(10, (sum, index) => sum + index, res => res == 75);View Code
第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; } }View Code
Pet構造:
public struct Pet { public string name; public Persion owner; public Pet(string name, Persion person) { this.name = name; owner = person; } }View Code
Persion_Pet構造:
public struct Persion_Pet { public string persionName; public string petName; public Persion_Pet(string persion, string pet) { persionName = persion; petName = pet; } }View Code
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();View Code
後果:
關鍵在於join會比擬第2個參數與第3個參數的前往值,只要相等時才會持續第4個參數。