0

我在 C# 中定义了以下 DTO 对象:

public class Record
{
    public List<EventType> EventTypes { get; set; }
}

并且在填充 List<Record> 而 EventType 被定义为枚举之后

public Enum EventType {
  UNLOCK = 1,
  LOCK = 2
}

现在我想从记录列表中制作一个类似于以下的报告:

count       Name
=====       ======
3           UNLOCK
1           LOCK

...通过使用(很可能是LINQ group by)。列出此列表的首选方法是什么?我假设我将不得不制作另一个 DTO 来保存该数据。

4

1 回答 1

3

根据您想要的结果数据类型,您可以使用以下任一种:

var result = records.SelectMany(x => x.EventTypes)
                    .GroupBy(x => x)
                    .ToDictionary(x => x.Key, x => x.Count());

var result = records.SelectMany(x => x.EventTypes)
                    .GroupBy(x => x)
                    .Select(x => new { Name = x.Key, Count = x.Count());

var result = records.SelectMany(x => x.EventTypes)
                    .GroupBy(x => x)
                    .Select(x => new YourType(x.Key, x.Count()));

第一个将生成一个字典,其中事件类型为键,其在列表中出现的次数为值。

Name第二个将导致具有两个属性和的匿名类型的可枚举Count

第三个将产生一个可枚举的类型YourType,该类型将事件类型及其出现次数传递给其构造函数。

于 2013-07-24T13:53:49.860 回答