Linq Group by
点击查看代码
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var list = new List<Emp>
{
new Emp{ Age = 1, Comp="11", Name="111"},
new Emp{ Age = 2, Comp="11", Name="222"},
new Emp{ Age = 3, Comp="11", Name="333"},
new Emp{ Age = 4, Comp="22", Name="444"},
new Emp{ Age = 5, Comp="22", Name="555"},
new Emp{ Age = 6, Comp="22", Name="666"},
new Emp{ Age = 7, Comp="22", Name="777"},
};
// avg count oldest
var eg = list.GroupBy(e => e.Comp);
foreach(var e in eg.ToDictionary(k=>k.Key, v=> v.Count())){
Console.WriteLine($"{e.Key} - {e.Value}");
}
Console.WriteLine("***********************************");
foreach(var e in eg.ToDictionary(k=>k.Key, v=> (int)v.Average(e=>e.Age))){
Console.WriteLine($"{e.Key} - {e.Value}");
}
Console.WriteLine("***********************************");
foreach(var e in eg.ToDictionary(k=>k.Key, v=> v.Max(e=>e.Age))){
Console.WriteLine($"{e.Key} - {e.Value}");
}
Console.WriteLine("***********************************");
foreach(var e in eg){
var max = e.Max(f=>f.Age);
Console.WriteLine($"{e.Key} - {e.FirstOrDefault(s=> s.Age == max).Name}");
}
}
public class Emp
{
public int Age{get;set;}
public string Name{get;set;}
public string Comp{get;set;}
}
}
输出:
11 - 3
22 - 4
***********************************
11 - 2
22 - 5
***********************************
11 - 3
22 - 7
***********************************
11 - 333
22 - 777