7

I've got a list of lists which I want to intersect:

List<List<int>> input = new List<List<int>>();
input.Add(new List<int>() { 1, 2, 4, 5, 8 });
input.Add(new List<int>() { 3, 4, 5 });
input.Add(new List<int>() { 1, 4, 5, 6 });

Output should be:

{ 4, 5 }

How can this be accomplished in a terse fashion?

mipe34
  • 5,596
  • 3
  • 26
  • 38
Larsenal
  • 49,878
  • 43
  • 152
  • 220
  • Do you need to be using Lists? why not use Hashsets? – Andrew Harry Mar 28 '10 at 05:35
  • possible duplicate of [Intersection of multiple lists with IEnumerable.Intersect()](http://stackoverflow.com/questions/1674742/intersection-of-multiple-lists-with-ienumerable-intersect) – Rawling Jan 13 '15 at 14:05

1 Answers1

16
var result = input.Cast<IEnumerable<int>>().Aggregate((x, y) => x.Intersect(y))
mqp
  • 70,359
  • 14
  • 95
  • 123
  • 1
    Sorry for making a mistake the first time, I forgot I would have to cast down to `IEnumerable`. – mqp Mar 28 '10 at 05:48