我正在尝试使用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();
}
答案 0 :(得分:3)
您需要存储输出:
var product2 = product.Union(new[] {
new ProductView
{
Id = 9999,
Active = true,
Name = "Test",
ProductTypeId=0,
}
});
product2.Dump();
除此之外,覆盖Equals行为会很有用 - 因为您可能只想使用Id字段检查相等性?
例如,如果你没有覆盖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件物品 - 这可能是你所期待的。
答案 1 :(得分:1)
如果您想以有意义的方式使用Equals
(除了通过refence进行比较),您需要覆盖GetHashCode
中的ProductView
和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; }
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>
并将其用于this overload of Union
。