Compare difference of two lists, .Except() algorithm to replace LINQ

632 Views Asked by At

I used to use .Except() to compare the difference of two List in C# by using LINQ like following.

List<string> APromotionProduct= GetAPromotionProduct(PrdA);
List<string> BPromotionProduct = GetBPromotionProduct<string>(PrdB);
List<string> tempList = new List<string>();
tempList = PromotionProduct.Except(XMLPromotionProduct).ToList();

However, my company is not using LINQ, we are on .NET 3. Therefore I can't use Enumerable.Except. How can I achieve the same purpose or how can I write the algorithm for .Except().

2

There are 2 best solutions below

3
On BEST ANSWER

If you can't use LINQ for whatever reason, this is the source:

static IEnumerable<TSource> ExceptIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) {
    Set<TSource> set = new Set<TSource>(comparer);
    foreach (TSource element in second) set.Add(element);
    foreach (TSource element in first)
        if (set.Add(element)) yield return element;
}

So you could use a HashSet<string>(ok, still .NET 3.5 needed):

public static IEnumerable<TSource> ExceptNoLinq<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) 
{
    HashSet<TSource> set = new HashSet<TSource>(comparer);
    foreach (TSource element in second) set.Add(element);
    foreach (TSource element in first)
        if (set.Add(element)) yield return element;
}

Then you can use:

var exceptItems = PromotionProduct.ExceptNoLinq(XMLPromotionProduct);
List<string> resultList = new List<string>(exceptItems);

If you are even on .NET 2:

public static IEnumerable<TSource> ExceptDotNet2<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
    var dict = new Dictionary<TSource, bool>(comparer);
    foreach (TSource element in second) dict.Add(element, true);
    foreach (TSource element in first)
    {
        if (!dict.ContainsKey(element))
        {
            dict.Add(element, true);
            yield return element;
        }
    }
}
0
On

Except() is an extension method from System.Linq. If you can refer this namespace in your file then you should be able to use it. This doesn't require a Visual studio. As long as you have access to the compiler you can compile and run your code.