Search code examples
c#linq

Find common items in multiple lists


I searched, but I found only answers which related to two lists. But what about when they are more than two?

List 1 = 1,2,3,4,5
List 2 = 6,7,8,9,1
List 3 = 3,6,9,2,0,1
List 4 = 1,2,9,0,5
List 5 = 1,7,8,6,5,4
List 6 = 1
List 7 =

How to get the common items? as you can see one of them is empty, so the common will be empty, but I need to skip empty lists.


Solution

  • var data = new [] {
        new List<int> {1, 2, 3, 4, 5},
        new List<int> {6, 7, 8, 9, 1},
        new List<int> {3, 6, 9, 2, 0, 1},
        new List<int> {1, 2, 9, 0, 5},
        new List<int> {1, 7, 8, 6, 5, 4},
        new List<int> {1},
        new List<int> {},
        null
    };
    
    var temp = data[0];
    foreach (var arr in data.Skip(1) )
       if (arr != null && arr.Count != 0)
          temp =  arr.Intersect(temp);