好吧,这取决于您要查找的数据。如果您不关心实际的 Date 值,只需将整数按它们分组(我怀疑也按它们排序),从对 Event 类的引用中您将拥有:
List<List<int>> byDate = evt.eventData
.GroupBy(d => d.date)
.OrderBy(g=>g.Key)
.Select(g => g.Select(v => v.someData)
.ToList())
.ToList();
但是,如果您关心日期,则可以采用两种方法。您最终可能会丢弃对 Data 类的任何引用:
Dictionary<DateTime, List<int>> byDate2 = evt.eventData
.GroupBy(d => d.date)
.OrderBy(g=>g.Key)
.ToDictionary(
g=>g.Key,
g => g.Select(v => v.someData)
.ToList());
或者您可以保留 Data 对象:
List<List<Data>> byDate = evt.eventData
.GroupBy(d => d.date)
.OrderBy(g => g.Key)
.Select(g => g.ToList())
.ToList();
但是假设您想通过对 TransferObject 类的引用来执行此操作。然后,您将执行几乎相同的操作,但需要使用 SelectMany 函数:
TransferObject txobj = new TransferObject(); // however this happens
List<List<int>> byDate = txobj.events
.SelectMany(evt=>evt.eventData
.GroupBy(d => d.date)
.OrderBy(g => g.Key)
.Select(g => g.Select(v => v.someData)
.ToList()))
.ToList();
Dictionary<DateTime, List<int>> byDate2 = txobj.events
.SelectMany(e=>e.eventData)
.GroupBy(d => d.date)
.OrderBy(g=>g.Key)
.ToDictionary(
g=>g.Key,
g => g.Select(v => v.someData)
.ToList());
List<List<Data>> byDate3 = txobj.events
.SelectMany(evt=>evt.eventData
.GroupBy(d => d.date)
.OrderBy(g => g.Key)
.Select(g => g.ToList()))
.ToList();
这里的关键是 SelectMany 函数本质上连接了普通 Select 将返回的一级集合,即
any IEnumerable<IEnumerable<T>> becomes an IEnumerable<T>.