2

我正在尝试Linq Union将其他记录添加到结果中,但 Union 不起作用。也许有人可以指出我正确的方向。

        public class ProductView
                    {
                        public int Id { get; set; }
                        public bool Active { get; set; }
                        public string Name { get; set; }
                        public int ProductTypeId { get; set; }
                        public int UserCount { get; set; }

        }

void Main()
{


var product = Products.Select(p => new ProductView
   {
        Id = p.Id,
        Active = p.Active,
        Name = p.Name,
        ProductTypeId = p.ProductTypeId,
        UserCount = 1
   }).ToList();


    //The new item is not jointed to the result above   
    product.Union(new[] {
            new ProductView
            {
            Id = 9999,
            Active = true, 
            Name = "Test",
            ProductTypeId=0,
            } 
         });


 product.Dump();                                          
}
4

2 回答 2

4

您需要存储输出:

 var product2 = product.Union(new[] {
    new ProductView
    {
    Id = 9999,
    Active = true, 
    Name = "Test",
    ProductTypeId=0,
    } 
 });

 product2.Dump();

除此之外,覆盖 Equals 行为会很有用——因为您可能只想使用 Id 字段来检查相等性?


例如,如果您不覆盖 Equals 行为,那么您将获得 Object 引用 equals,如下所示:

void Main()
{

    var list = new List<Foo>()
    {
    new Foo() { Id = 1},
    new Foo() { Id = 2},
    new Foo() { Id = 3},
    };

    var list2 = new List<Foo>()
    {
    new Foo() { Id = 1},
    new Foo() { Id = 2},
    new Foo() { Id = 3},
    };

    var query = list.Union(list2);

    query.Dump();

}

// Define other methods and classes here

public class Foo
{
 public int Id {get;set;}
}

生产六件商品!

但是,如果您将 Foo 更改为:

public class Foo
{
    public int Id {get;set;}

    public override bool Equals(object obj)
    {
     if (obj == null || !(obj is Foo)) return false;
     var foo= (Foo)obj;
     return this.Id == foo.Id;
    }

    public override int GetHashCode()
    {
         return this.Id.GetHashCode();
    }    
}

那么您将获得 3 件物品 - 这可能是您所期望的。

于 2013-01-31T13:11:48.677 回答
1

如果您想以有意义的方式使用(除了通过引用进行比较),您需要覆盖EqualsGetHashCodeProductViewUnion

public class ProductView
{
    public int Id { get; set; }
    public bool Active { get; set; }
    public string Name { get; set; }
    public int ProductTypeId { get; set; }
    public int UserCount { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null || !(obj is ProductView)) return false;
        ProductView pv2 = (ProductView)obj;
        return this.Id == pv2.Id;
    }

    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }
}

您也可以IEqualityComparer<ProductView>以类似的方式实现 ,并将其用于Union.

于 2013-01-31T13:14:50.010 回答