组列表<;T>;并创建带有count的新列表

本文关键字:列表 count 新列表 创建 lt gt | 更新日期: 2023-09-27 18:25:43

我有下一个类和列表:

public class cls1
{
  public string prop1 {get; set;}
  public string prop2 {get; set;}
  public string prop3 {get; set;}
}
public List<cls1> list = new List(cls1)();

我需要按prop2字段对列表进行分组,并对该字段进行计数,最后按计数降序排列。

组列表<;T>;并创建带有count的新列表

你可以做:

var query = list.GroupBy(r => r.prop2)
                .Select(grp => new
                {
                    Key = grp.Key,
                    Count = grp.Count(),
                })
                .OrderByDescending(r => r.Count);