LINQ and Intersect

Assume that we have 3 list of integer.

They are

            
var listA = new List<int> {1,2,3,4,5};
var listB = new List<int> {2, 3, 6, 8,9 };
var listC = new List<int> { 3, 8, 13, 14, 15 };

The intersect of these 3 list are {3}

How can we get this result by LINQ?

It is pretty simple.

I provide two ways to do it.

Method A:

        public static List<T> ToIntersectAll<T>(this List<List<T>> lists)
        {
            HashSet<T> hashSet = null;
            foreach (var list in lists)
            {
                if (hashSet == null)
                {
                    hashSet = new HashSet<T>(list);
                }
                else
                {
                    hashSet.IntersectWith(list);
                }
            }
            return hashSet == null ? new List<T>() : hashSet.ToList();
        }

Method B:

        public static List<T> ToSimpleIntersectAll<T>(this List<List<T>> lists)
        {
            return lists.Aggregate((previousList, nextList) => previousList.Intersect(nextList).ToList());
        }

By calling these two methods, we need a List of List.

var listOfList = new List<List<int>> {listA, listB, listC};

After this, we can simple call the methods.

            var resultA = listOfList.ToIntersectAll();
            var resultB = listOfList.ToSimpleIntersectAll();

That is it.