比较两个列表的差异,.Except() 算法替代 LINQ

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

我曾经使用 .Except() 通过使用 LINQ 来比较 C# 中两个列表的差异,如下所示。

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

但是,我的公司没有使用 LINQ,我们使用的是 .NET 3。 因此我不能使用 Enumerable.Except。我怎样才能达到同样的目的 或者我如何编写 .Except().

的算法

如果您出于某种原因不能使用 LINQ,这是 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;
}

因此您可以使用 HashSet<string>(好的,仍然需要 .NET 3.5):

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;
}

那么你可以使用:

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

如果您使用的是 .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;
        }
    }
}

Except() 是 System.Linq 的扩展方法。如果您可以在文件中引用此命名空间,那么您应该可以使用它。这不需要 Visual studio。只要您可以访问编译器,您就可以编译和 运行 您的代码。