Union Vs Concat in Linq

前端 未结 3 1361
心在旅途
心在旅途 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:12

    Union returns Distinct values. By default it will compare references of items. Your items have different references, thus they all are considered different. When you cast to base type X, reference is not changed.

    If you will override Equals and GetHashCode (used to select distinct items), then items will not be compared by reference:

    class X
    {
        public int ID { get; set; }
    
        public override bool Equals(object obj)
        {
            X x = obj as X;
            if (x == null)
                return false;
            return x.ID == ID;
        }
    
        public override int GetHashCode()
        {
            return ID.GetHashCode();
        }
    }
    

    But all your items have different value of ID. So all items still considered different. If you will provide several items with same ID then you will see difference between Union and Concat:

    var lstX1 = new List { new X1 { ID = 1, ID1 = 10 }, 
                               new X1 { ID = 10, ID1 = 100 } };
    var lstX2 = new List { new X2 { ID = 1, ID2 = 20 }, // ID changed here
                               new X2 { ID = 20, ID2 = 200 } };
    
    var a5 = lstX1.Cast().Union(lstX2.Cast());  // 3 distinct items
    var a6 = lstX1.Cast().Concat(lstX2.Cast()); // 4
    

    Your initial sample works, because integers are value types and they are compared by value.

提交回复
热议问题