1

I have a list of User objects (List<User>). Every object in this list has a list of events (List<Event>). I need to create a new collection of Events with the common objects in all lists of Events in every user. I mean every user in base collection has every event in new collection of Events.

I think it can be done using foreach loop, but I hope there is more elegant way to do this using LINQ.

Hope, you'll help. Thank you.

4

2 回答 2

1

You can use the Enumerable.Interstect and Enumerable.Aggregate methods

// 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-30T20:25:44.213 回答
0

The idea is to select all events in all users, then create groups of equal events, select only those groups with as many events as users, and then just one event for each of these groups.

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)
于 2013-03-30T20:35:32.073 回答