linq 分组取各组最大值

时间:2021-05-05 15:13:37
static List<User> list1 = new List<User>()
        {
            new User(){id=1,name="张三"},
            new User(){id=2,name="张三"},
            new User(){id=3,name="张三"},
            new User(){id=4,name="李四"},
            new User(){id=5,name="李四"},
            new User(){id=6,name="王五"},
        };

        static void Main()
        {
            var q = from d in list1
                    group d by d.name into g
                    select new
                    {
                        Id = g.Max(x => x.id),
                        Name = g.Key
                    };
                q.ToList().ForEach(x=>Console.WriteLine(x.Id+" "+x.Name+" "));
            Console.ReadLine();
        }


结果:

3  张三

5  李四

6  王五