Union Vs Concat in Linq

前端 未结 3 1367
心在旅途
心在旅途 2020-12-02 21:55

I have a question on Union and Concat. I guess both are behaving same in case of List .

var a1 = (new[] { 1,          


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 22:16

    Union and Concat behave the same since Union can not detect duplicates without a custom IEqualityComparer. It's just looking if both are the same reference.

    public class XComparer: IEqualityComparer
    {
        public bool Equals(X x1, X x2)
        {
            if (object.ReferenceEquals(x1, x2))
                return true;
            if (x1 == null || x2 == null)
                return false;
            return x1.ID.Equals(x2.ID);
        }
    
        public int GetHashCode(X x)
        {
            return x.ID.GetHashCode();
        }
    }
    

    Now you can use it in the overload of Union:

    var comparer = new XComparer();
    a5 = lstX1.Cast().Union(lstX2.Cast(), new XComparer()); 
    

提交回复
热议问题