快速获取两个List<>之间差异的方法对象

时间:2013-09-25 18:17:21

标签: c# list

如何让itemsToRemove仅包含“bar one”,itemsToAdd只包含“bar 5”?

我正在尝试使用“除外”,但显然我使用的不正确。

var oldList = new List<Foo>();
oldList.Add(new Foo(){ Bar = "bar one"});
oldList.Add(new Foo(){ Bar = "bar two"});
oldList.Add(new Foo(){ Bar = "bar three"});
oldList.Add(new Foo(){ Bar = "bar four"});



var newList = new List<Foo>();
newList.Add(new Foo(){ Bar = "bar two"});
newList.Add(new Foo(){ Bar = "bar three"});
newList.Add(new Foo(){ Bar = "bar four"});
newList.Add(new Foo(){ Bar = "bar five"});


var itemsToRemove = oldList.Except(newList);    // should only contain "bar one"
var itemsToAdd = newList.Except(oldList);    // should only contain "bar one"


foreach(var item in itemsToRemove){
    Console.WriteLine(item.Bar + " removed");
    // currently says 
    // bar one removed
    // bar two removed
    // bar three removed
    // bar four removed
}


foreach(var item in itemsToAdd){
    Console.WriteLine(item.Bar + " added");
    // currently says 
    // bar two added
    // bar three added
    // bar four added
    // bar five added
}

5 个答案:

答案 0 :(得分:7)

除非您提供自定义比较器(您还没有),否则

Except将使用相关对象的默认EqualsGetHashCode方法来定义对象的“相等性”。在这种情况下,它将比较对象的引用,而不是它们的Bar值。

一种选择是创建一个IEqualityComparer<Foo>来比较Bar属性,而不是对象对象本身的引用。

public class FooComparer : IEqualityComparer<Foo>
{
    public bool Equals(Foo x, Foo y)
    {
        if (x == null ^ y == null)
            return false;
        if (x == null && y == null)
            return true;
        return x.Bar == y.Bar;
    }

    public int GetHashCode(Foo obj)
    {
        if (obj == null)
            return 0;
        return obj.Bar.GetHashCode();
    }
}

另一种选择是创建一个Except方法,该方法接受一个选择器来比较值。我们可以创建这样的方法,然后使用它:

public static IEnumerable<TSource> ExceptBy<TSource, TKey>(
    this IEnumerable<TSource> first,
    IEnumerable<TSource> second,
    Func<TSource, TKey> keySelector,
    IEqualityComparer<TKey> comparer = null)
{
    comparer = comparer ?? EqualityComparer<TKey>.Default;
    var set = new HashSet<TKey>(second.Select(keySelector), comparer);
    return first.Where(item => set.Add(keySelector(item)));
}

这允许我们写:

var itemsToRemove = oldList.ExceptBy(newList, foo => foo.Bar);
var itemsToAdd = newList.ExceptBy(oldList, foo => foo.Bar);

答案 1 :(得分:2)

您的逻辑是合理的,但用于比较两个类的Except默认行为是通过引用来进行的。由于您有效地创建了两个包含8个不同对象的列表(无论其内容如何),因此不会有两个相等的对象。

但是,您可以使用Except overload that takes an IEqualityComparer。例如:

public class FooEqualityComparer : IEqualityComparer<Foo> 
{
    public bool Equals(Foo left, Foo right) 
    {
        if(left == null && right == null) return true;

        return left != null && right != null && left.Bar == right.Bar;
    }

    public int GetHashCode(Foo item)
    {
        return item != null ? item.Bar.GetHashcode() : 0;
    }
}

// In your code

var comparer = new FooEqualityComparer();
var itemsToRemove = oldList.Except(newList, comparer ); 
var itemsToAdd = newList.Except(oldList, comparer); 

答案 2 :(得分:1)

对于Servy的回答,这主要是对这一点采取更一般的方法的重复:

public class PropertyEqualityComparer<TItem, TKey> : EqualityComparer<Tuple<TItem, TKey>>
{
    readonly Func<TItem, TKey> _getter;
    public PropertyEqualityComparer(Func<TItem, TKey> getter)
    {
        _getter = getter;
    }

    public Tuple<TItem, TKey> Wrap(TItem item) {
        return Tuple.Create(item, _getter(item));
    }

    public TItem Unwrap(Tuple<TItem, TKey> tuple) {
        return tuple.Item1;
    }

    public override bool Equals(Tuple<TItem, TKey> x, Tuple<TItem, TKey> y)
    {
        if (x.Item2 == null && y.Item2 == null) return true;
        if (x.Item2 == null || y.Item2 == null) return false;
        return x.Item2.Equals(y.Item2);
    }

    public override int GetHashCode(Tuple<TItem, TKey> obj)
    {

        if (obj.Item2 == null) return 0;
        return obj.Item2.GetHashCode();
    }
}

public static class ComparerLinqExtensions {
    public static IEnumerable<TSource> Except<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keyGetter)
    {
        var comparer = new PropertyEqualityComparer<TSource, TKey>(keyGetter);
        var firstTuples = first.Select(comparer.Wrap);
        var secondTuples = second.Select(comparer.Wrap);
        return firstTuples.Except(secondTuples, comparer)
                          .Select(comparer.Unwrap);
    }
}
// ...
var itemsToRemove = oldList.Except(newList, foo => foo.Bar);
var itemsToAdd = newList.Except(oldList, foo => foo.Bar);

对于没有异常等式语义的任何类,这应该可以正常工作,调用object.Equals()覆盖而不是IEquatable<T>.Equals()是不正确的。值得注意的是,这对于匿名类型可以正常工作。

答案 3 :(得分:0)

这是因为您要比较Foo类型的对象,而不是类型string的属性栏。尝试:

var itemsToRemove = oldList.Select(i => i.Bar).Except(newList.Select(i => i.Bar));
var itemsToAdd = newList.Select(i => i.Bar).Except(oldList.Select(i => i.Bar));

答案 4 :(得分:0)

在您的数据对象上实现IComparable;我认为你被参考比较所困扰。如果将Foo更改为字符串,则代码可以正常工作。

        var oldList = new List<string>();
        oldList.Add("bar one");
        oldList.Add("bar two");
        oldList.Add("bar three");
        oldList.Add("bar four");

        var newList = new List<string>();
        newList.Add("bar two");
        newList.Add("bar three");
        newList.Add("bar four");
        newList.Add("bar five");

        var itemsToRemove = oldList.Except(newList);    // should only contain "bar one"
        var itemsToAdd = newList.Except(oldList);    // should only contain "bar one"

        foreach (var item in itemsToRemove)
        {
            Console.WriteLine(item + " removed");
        }


        foreach (var item in itemsToAdd)
        {
            Console.WriteLine(item + " added");
        }