联盟VS的毗连Linq中 [英] Union Vs Concat in Linq

查看:128
本文介绍了联盟VS的毗连Linq中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对联盟的毗连的问题。我想两者都在名单,LT的情况下表现一致; T>

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

var a1 = (new[] { 1, 2 }).Union(new[] { 1, 2 });             // O/P : 1 2
var a2 = (new[] { 1, 2 }).Concat(new[] { 1, 2 });            // O/P : 1 2 1 2

var a3 = (new[] { "1", "2" }).Union(new[] { "1", "2" });     // O/P : "1" "2"
var a4 = (new[] { "1", "2" }).Concat(new[] { "1", "2" });    // O/P : "1" "2" "1" "2"



上述结果预计,

The above result are expected,

名单,LT的柜面; T> 我收到同样的效果。

class X
{
    public int ID { get; set; }
}

class X1 : X
{
    public int ID1 { get; set; }
}

class X2 : X
{
    public int ID2 { get; set; }
}

var lstX1 = new List<X1> { new X1 { ID = 10, ID1 = 10 }, new X1 { ID = 10, ID1 = 10 } };
var lstX2 = new List<X2> { new X2 { ID = 10, ID2 = 10 }, new X2 { ID = 10, ID2 = 10 } };

var a5 = lstX1.Cast<X>().Union(lstX2.Cast<X>());     // O/P : a5.Count() = 4
var a6 = lstX1.Cast<X>().Concat(lstX2.Cast<X>());    // O/P : a6.Count() = 4



但两者都表现柜面相同列表< T>

任何建议,请

推荐答案

联盟收益鲜明值。默认情况下,将比较项目的引用。您的项目有不同的引用,因此,他们都被认为是不同的。当你施放基地键入 X ,引用不会改变。

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.

如果您将覆盖等于的GetHashCode (用来选择不同的项目),则项目将无法相比的参照:

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();
    }
}



但是,所有的项目有不同的价值 ID 。因此,所有的项目仍然被认为是不同的。如果你提供几个项目具有相同的 ID 然后你会看到联盟之间的区别的毗连

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<X1> { new X1 { ID = 1, ID1 = 10 }, 
                           new X1 { ID = 10, ID1 = 100 } };
var lstX2 = new List<X2> { new X2 { ID = 1, ID2 = 20 }, // ID changed here
                           new X2 { ID = 20, ID2 = 200 } };

var a5 = lstX1.Cast<X>().Union(lstX2.Cast<X>());  // 3 distinct items
var a6 = lstX1.Cast<X>().Concat(lstX2.Cast<X>()); // 4

您最初的样本工程,因为整数是值类型,它们按值进行比较。

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

这篇关于联盟VS的毗连Linq中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆