C # Use of Aggregate and Join in Enumerable,
Reference page:
Http://www.yuanjiaocheng.net/ASPNET-CORE/asp.net-core-environment.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/newproject.html
Http://www.yuanjiaocheng.net/webapi/web-api-gaisu.html
Http://www.yuanjiaocheng.net/webapi/create-web-api-proj.html
Http://www.yuanjiaocheng.net/webapi/test-webapi.html
Directly run the Code:
IEnumerable<int> list = Enumerable.Range(2, 10);int all = list.Aggregate((sum, index) => sum + index);
View Code
Debugging, the first call, found that sum and index respectively take the list of 1st and 2nd values:
F5 next, we found that the index was added to sum (sum + = index), then index took the next value, and accumulated to sum. Repeat this step until the value in the list is obtained:
The final calculation result is 65.
The other two overload functions:
int all = list.Aggregate(10, (sum, index) => sum + index);
View Code
The 2nd parameters are the same as the parameters in the previous example. The value of the cumulative list is the initial value and will be applied to the cumulative value. Here, the value is equivalent to 10 plus 65, and the calculation result is 75.
bool is75 = list.Aggregate(10, (sum, index) => sum + index, res => res == 75);
View Code
1st 2nd parameters are the same as above. 3rd parameters are used to determine the cumulative result. In this example, the cumulative result is 75 and the calculated result is true.
We can find that list. aggregate (sum, index) => sum + index) is actually list. the exception of Aggregate (0, (sum, index) => sum + index) is equivalent to the initial value of 0.
==============================
Use Join to view code
Persion structure:
public struct Persion { public int index; public string name; public Persion(int index, string nm) { this.index = index; name = nm; } }
View Code
Pet structure:
public struct Pet { public string name; public Persion owner; public Pet(string name, Persion person) { this.name = name; owner = person; } }
View Code
Persion_Pet structure:
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, "Zhang San"); Persion p2 = new Persion (2, "Li Si"); Persion p3 = new Persion (3, "Lu Ren jia "); list <Persion> people = new List <Persion> () {p1, p2, p3}; Persion p4 = new Persion (4, ""); pet dog = new Pet ("Huanhuan", p1); Pet cat = new Pet ("Mimi", 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
Result:
The key is that join compares the return values of 2nd parameters with those of 3rd parameters. Only when the values are equal will 4th parameters continue.