Background: In the output list, you often need to group by a field, such as in the Output city list, according to the first letter grouping, output student list, according to the grade group, and then the results of the group sorted by other fields.
If the following Stu student classes exist, the code is as follows:
1 Public classSTU2 {3 Public intID {Get;Set; }4 Public stringName {Get;Set; }5 Public intAge {Get;Set; }6 Public stringCity {Get;Set; }7}
The following list of students exists:
1List<stu> stulist =NewList<stu>()2 {3 NewStu{id=1, name="Lily", age= -, city="NewYork"},4 NewStu{id=2, name="Lucy", age= -, city="NewYork"},5 NewStu{id=1, name="Lilei", age= -, city="Beijing"}6};
First, according to the city group, in the same city students, according to the age of sorting, output, the code is as follows:
1 foreach(igrouping<string,stu> GroupinchStulist.groupby (c=>c.city))2 {3Console.WriteLine ("the current city is"+Group. Key);4 foreach(STU STUinchGroup. (a=>a.age))5 {6Console.Write (Stu. name+";");7 }8 Console.WriteLine ();9}
Note that igroupoing has two parameters, the first parameter corresponds to the type of the grouping field, that is, if the type of the first parameter is a string, if it is grouped by city, the parameter type should be int if it is grouped by age. The second argument, which corresponds to the type of the list element, is Stu in this case.
Grouping output elements for generic lists in C #