Personally, I would try to avoid O(nm) performance by building a
dictionary from one list, and comparing to the other - that should
give (roughly) O(n+m) [much better].
Something like below.
Marc
using System;
using System.Collections.Generic;
static class Program
{
static void Main()
{
List<int> lhs = new List<int> { 1, 2, 3, 4, 5, 6 },
rhs = new List<int> { 2, 4, 5, 6, 7 };
foreach (int value in Intersect(lhs, rhs))
{
Console.WriteLine(value);
}
}
static IEnumerable<T> Intersect<T>(IList<T> lhs, IList<T> rhs)
{
if(lhs == null) throw new ArgumentNullException("lhs");
if(rhs == null) throw new ArgumentNullException("rhs");
// build the dictionary from the shorter list
if (lhs.Count > rhs.Count)
{
IList<T> tmp = rhs;
rhs = lhs;
lhs = tmp;
}
Dictionary<T, bool> lookup = new Dictionary<T, bool>();
foreach (T item in lhs)
{
if (!lookup.ContainsKey(item)) lookup.Add(item, true);
}
foreach (T item in rhs)
{
if (lookup.ContainsKey(item))
{
lookup.Remove(item); // prevent duplicates
yield return item;
}
}
}
}