c#LinqLamda表达式使⽤GroupBy分组
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
groupby分组List<Person> persons1 = new List<Person>();
persons1.Add(new Person("张三", "男", 20, 1500, DateTime.Now.AddYears(1)));
persons1.Add(new Person("王成", "男", 32, 3200, DateTime.Now.AddYears(2)));
persons1.Add(new Person("李丽", "⼥", 19, 1700, DateTime.Now.AddYears(3)));
persons1.Add(new Person("何英", "⼥", 35, 3600, DateTime.Now.AddYears(4)));
persons1.Add(new Person("何英", "⼥", 18, 1600, DateTime.Now.AddYears(5)));
//写法1:lamda 表达式写法(推荐)
var ls = persons1.GroupBy(a => a.Name).Select(g => (new Test { name = g.Key, count = g.Count(),
ageC = g.Sum(item => item.Age), moneyC = g.Sum(item => item.Money), birth=g.Max(item=>item.Birthday) }));            //写法2:类SQL语⾔写法 最终编译器会把它转化为lamda表达式
var ls2 = from ps in persons1
group ps by ps.Name
into g
select new Test
{
name = g.Key,
count = g.Count(),
ageC = g.Sum(item => item.Age),
moneyC = g.Sum(item => item.Money),
birth=g.Max(item=>item.Birthday)
};
List<Test> l1= ls.ToList();
List<Test> l2 = ls2.ToList();
Console.ReadKey();
}
}
public class Test
{
public string name { get; set; }
public int count { get; set; }
public int ageC { get; set; }
public int ageC { get; set; }
public int moneyC { get; set; }
public DateTime birth { get; set; }
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
public int Money { get; set; }
public DateTime Birthday { get; set; }
public Person(string name, string sex, int age, int money, DateTime birthday)        {
Name = name;
Age = age;
Sex = sex;
Money = money;
Birthday = birthday;
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。