我有一个用户对象列表(List<User>
)。此列表中的每个对象都有一个事件列表(List<Event>
)。我需要创建一个新的事件集合,其中包含每个用户的所有事件列表中的公共对象。我的意思是,基础集合中的每个用户都有新的事件集合中的每个事件。
我认为这可以使用foreach循环来完成,但我希望有更优雅的方式来使用LINQ来完成这项工作。
霍普你会帮忙的。谢谢。
发布于 2013-03-31 04:25:44
您可以使用Enumerable.Interstect
和Enumerable.Aggregate
方法
// first get events for first user
IEnumerable<Event> seed = userList.First().Events;
// intersect with events for users (except the first)
var commonItems = userList.Skip(1).Aggregate(seed, (s, u) => s.Intersect(u.Events));
发布于 2013-03-31 04:35:32
其思想是选择所有用户中的所有事件,然后创建相等事件的组,仅选择事件与用户数量相同的组,然后为每个组只选择一个事件。
var x = users.SelectMany(u => u.Events) // select all events at once
.GroupBy(e => e) // group them
.Where(g => g.Count() == users.Count) // select groups with as many events as users
.Select(g => g.Key); // select just one event for each group (the others are the same)
https://stackoverflow.com/questions/15723097
复制相似问题