How to find common objects in multiple lists?

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.

Upvotes: 1

Views: 1276

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149108

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));

Upvotes: 1

Juli&#225;n Urbano
Juli&#225;n Urbano

Reputation: 8488

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)

Upvotes: 0

Related Questions