Get Intersection between two List - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Get Intersection between two List

Demo Code


using System.Text;
using System.Collections.Generic;
using System;//from ww w .  j  a  va 2  s .  c o m

public class Main{
    
        public static List<T> GetIntersection<T>(List<T> list1, List<T> list2) where T : IComparable
        {
            List<T> largList = list1.Count > list2.Count ? list1 : list2;
            List<T> smallList = largList == list1 ? list2 : list1;
            
            largList.Sort();

            int minIndex = 0;

            List<T> result = new List<T>();
            foreach (T tmp in smallList)
            {
                if (CollectionHelper.BinarySearch<T>(largList, tmp, out minIndex))
                {
                    result.Add(tmp);
                }
            }

            return result;
        }
}

Related Tutorials