1

我如何才能itemsToRemove只包含“小节一”,而itemsToAdd只包含“小节五”?

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

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

5 回答 5

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);
于 2013-09-25T18:21:45.357 回答
2

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

但是,您可以使用Except采用 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); 
于 2013-09-25T18:23:34.110 回答
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()值得注意的是,这将适用于匿名类型。

于 2013-09-25T18:36:40.163 回答
0

这是因为您正在比较 type 的对象Foo,而不是 type 的属性 Bar 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));
于 2013-09-25T18:21:18.663 回答
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");
        }
于 2013-09-25T18:25:50.090 回答