gpt4 book ai didi

Linq Union 不工作

转载 作者:行者123 更新时间:2023-12-02 22:14:59 24 4
gpt4 key购买 nike

我正在尝试使用 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();
}

最佳答案

您需要存储输出:

 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 个项目 - 这可能是您所期望的。

关于Linq Union 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14626555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com