Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect a collection of collections in LINQ

Tags:

c#

linq

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?

like image 585
Larsenal Avatar asked Mar 28 '10 05:03

Larsenal


1 Answers

var result = input.Cast<IEnumerable<int>>().Aggregate((x, y) => x.Intersect(y))
like image 134
mqp Avatar answered Sep 27 '22 00:09

mqp