Using Linq Except not Working as I Thought

后端 未结 5 1417
梦如初夏
梦如初夏 2020-11-28 10:26

List1 contains items { A, B } and List2 contains items { A, B, C }.

What I need is to be returned { C }

5条回答
  •  时光说笑
    2020-11-28 11:20

    So just for completeness...

    // Except gives you the items in the first set but not the second
        var InList1ButNotList2 = List1.Except(List2);
        var InList2ButNotList1 = List2.Except(List1);
    // Intersect gives you the items that are common to both lists    
        var InBothLists = List1.Intersect(List2);
    

    Edit: Since your lists contain objects you need to pass in an IEqualityComparer for your class... Here is what your except will look like with a sample IEqualityComparer based on made up objects... :)

    // Except gives you the items in the first set but not the second
            var equalityComparer = new MyClassEqualityComparer();
            var InList1ButNotList2 = List1.Except(List2, equalityComparer);
            var InList2ButNotList1 = List2.Except(List1, equalityComparer);
    // Intersect gives you the items that are common to both lists    
            var InBothLists = List1.Intersect(List2);
    
    public class MyClass
    {
        public int i;
        public int j;
    }
    
    class MyClassEqualityComparer : IEqualityComparer
    {
        public bool Equals(MyClass x, MyClass y)
        {
            return x.i == y.i &&
                   x.j == y.j;
        }
    
        public int GetHashCode(MyClass obj)
        {
            unchecked
            {
                if (obj == null)
                    return 0;
                int hashCode = obj.i.GetHashCode();
                hashCode = (hashCode * 397) ^ obj.i.GetHashCode();
                return hashCode;
            }
        }
    }
    

提交回复
热议问题