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 class Form1:form {public Form1 () {InitializeComponent (); } list<person> persons1 = new list<person> (); private void Form1_Load (object sender, EventArgs e) {initform (); } private void InitForm () {//form initialize PERSONS1. ADD (New person ("Zhang San", "male", 20, 1500)); Persons1. ADD (New person ("Wang Cheng", "male", 32, 3200)); Persons1. ADD (New person ("Lily", "female", 19, 1700)); Persons1. ADD (New person ("joint", "female", 35, 3600)); Persons1. ADD (New person ("joint", "female", 18, 1600)); Datagridview1.datasource = persons1; } private void Button1_Click (object sender, EventArgs e) {//******* pairs the collection by name belongs to group GR Oupby query The fields included in the ********//results://1, grouped keywords: Name = g.key//2, number of each group: Count = G.count () 3, each group ofTotal Age: Agec = g.sum (item + item. Age)//4, sum of revenue per grouping: MONEYC = g.sum (item + Item). Money)//notation 1:lamda expression (recommended) var ls = 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 LAMDA expression var ls2 = from PS in PERSONS1 Group PS by PS. Name into G select 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. Used to place the list generic in////</summary> public class Person {public string Name {get; set;} public int Age {get;private set;}public string Sex {get; set;} public int Money {get; set;} Public person (string name, string sex, int. int, int money) {name = name; Age = age; sex = sex; Money = money; } }
C # LINQ and LAMDA expression application experience GroupBy grouping