示例1:
GroupBy 分组在List<>泛型中的应用
原表:
按姓名Nam 分组后结果:
//写法1:lamda 表达式写法(推荐) 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) }));
//写法2:类SQL语言写法 最终编译器会把它转化为lamda表达式 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) };
补充下,如果是多列分组的话:
var ls = persons1.GroupBy(a => new { a.Name, a.Age }).Select(g => (new { name1 = g.Key, count1 = g.Count(), ageC1 = g.Sum(item => item.Age), moneyC1 = g.Sum(item => item.Money) }));
结果中的name1实际上成为一个对象,包含Name和Age两个属性。