This article was reproduced from: http://www.cnblogs.com/han1982/p/4138163.html
Example 1:
Application of GroupBy grouping in list<> generics
Original table:
Results by name Nam Group:
Lamda queries on a DataTable must be added in a reference to the project System.Data.DataSetExtensions
Code:
Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } List<Person> persons1 =NewList<person>(); Private voidForm1_Load (Objectsender, EventArgs e) {initform (); } Private voidinitform () {//form Initializationpersons1. ADD (NewPerson ("Zhang San","male", -, the)); Persons1. ADD (NewPerson ("Wang Cheng","male", +,3200)); Persons1. ADD (NewPerson ("Lili","female", +,1700)); Persons1. ADD (NewPerson ("Joint","female", *,3600)); Persons1. ADD (NewPerson ("Joint","female", -, the)); Datagridview1.datasource=persons1; } Private voidButton1_Click (Objectsender, EventArgs e) { //******* the collection by name belongs to group GroupBy query ********//fields included in the results://1. Group keyword: Name = G.key//2. Number of each group: Count = G.count ()//3. The sum of the ages of each grouping: AGEC = g.sum (item + Item). Age)//4. Sum of revenue for each grouping: MONEYC = g.sum (item + Item). Money)//notation 1:LAMDA expression (recommended) varls = persons1. GroupBy (A = a.name). Select (g = (New{name = G.key, Count = G.count (), AGEC = g.sum (item = Item). Age), MONEYC = g.sum (item =item. (Money)})); //notation 2: Class SQL language The final compiler translates it into a LAMDA expression varLS2 = fromPsinchPERSONS1 Group PS by PS. Name into GSelect New{name = G.key, Count = G.count (), AGEC = g.sum (item = Item). Age), MONEYC = g.sum (item =item. Money)}; Datagridview1.datasource=ls. ToList (); //Datagridview1.datasource = ls2. ToList (); } } /// <summary> ///manually design a person class. For placing in a list generic/// </summary> Public classPerson { Public stringName {Get;Set; } Public intAge {Get;Private Set; } Public stringSex {Get;Set; } Public intMoney {Get;Set; } PublicPerson (stringNamestringSexintAgeintMoney ) {Name=name; Age=Age ; Sex=sex; Money=Money ; } }
(Turn) C # LINQ and LAMDA expression application experience GroupBy grouping