3

I have a few list. Their count isn't clear.

For example (for 4 list):

List1   List2    List3     List4 
-----   -----    -----     -----
  1       2        3         4
  2       4        8         3   
  3       8        4         5   
  4       11       6         1    
  5       3        7         7    
  6       9        11        9

I want to find the items that are common. It can do with T-SQL in MSSQL.

The result will be like that:

ResultList : (3, 4)

How is it done with Lambda Expression ?

Sinan AKYAZICI
  • 3,942
  • 5
  • 35
  • 60

5 Answers5

5

You can use Enumerable.Intersect

var commonItems = list1.Intersect(list2).Intersect(list3).Intersect(list4);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

For an arbitrary number of lists, you would do something like this:

var List<List<int>> lists; //This contains the lists I assume...
var result = lists.Skip(1).Aggregate(lists.First(), (accum, cur) => accum.Intersect(cur));
GregRos
  • 8,667
  • 3
  • 37
  • 63
  • Thanks @GregRos, I already had the intersection solved but was about ready to do some hardcoding for arbitrary number of lists. This was just the piece I was missing. – Fjarskiptagervitungl Nov 24 '15 at 08:32
1
list1.Intersect(list2).Intersect(list3).Intersect(list4);
willvv
  • 8,439
  • 16
  • 66
  • 101
0

Are you looking for Intersect?

qJake
  • 16,821
  • 17
  • 83
  • 135
0

You can use Enumerable.Intersect and intersect List1 with List1 and its result with List3 and so on.

    List1.Intersect(List2).Intersect(List3).Intersect(List4)
Ani
  • 10,826
  • 3
  • 27
  • 46