我有一个产品(草稿)列表,需要与数据库匹配(保存)并进行一些计算。当我们检索或创建时,它们是相同的对象。如果我将Reference1(草稿)与Reference1(已保存)和Reference2(草稿)与Reference2(已保存)匹配,那么它会很顺利,但是他们更改了数据库表并且还必须修改Object,其中,它们可以覆盖Reference1使用OverrideReference1字段的值。 OverrideReference1是在Reference1上使用的高优先级(如果不是空的)。我也使用string.IsNullOrEmpty(s.OverrideReference1) ? s.Reference1 : s.OverrideReference1
加入但没有运气
我使用以下代码查询结果,但在加入两个对象时出错。
var draft = new List<Product>
{
new Product { ProductName ="Phone", Quantity = 1000, Reference1 = "RC1", OverrideReference1 = string.Empty, Status = "Draft", Reference2 = string.Empty },
new Product { ProductName ="Phone", Quantity = 2000, Reference1 = "RC2", OverrideReference1 = string.Empty, Status = "Draft", Reference2 = string.Empty },
new Product { ProductName ="Phone", Quantity = 3000, Reference1 = "RC3", OverrideReference1 = string.Empty, Status = "Draft", Reference2 = string.Empty },
new Product { ProductName ="Phone", Quantity = 3000, Reference1 = string.Empty, OverrideReference1 = string.Empty, Status = "Draft", Reference2 = "CC1" },
};
var saved = new List<Product>
{
new Product { ProductName ="Phone", Quantity = 500, Reference1 = "RC1", OverrideReference1 = "RC3", Status = "Saved" },
new Product { ProductName ="Phone", Quantity = 3000, Reference1 = string.Empty, OverrideReference1 = string.Empty, Status = "Saved", Reference2 = "CC1" },
};
var results = (from d in draft
join s in saved on new { d.Reference1, d.Reference2 } equals new { s.OverrideReference1 ?? s.Reference1, s.Reference2 }
select new Product
{
ProductName = d.ProductName,
Quantity = s.Quantity - d.Quantity,
Reference1 = d.Reference1,
Status = d.Status
}).ToList();
答案 0 :(得分:0)
列名必须与您的问题相同。
此行中的问题:
join s in saved on new { d.Reference1, d.Reference2 } equals
new { s.OverrideReference1 ?? s.Reference1, s.Reference2 }
更新
join s in saved on new {
(string?)Reference1 = d.Reference1,
(string?)Reference2= d.Reference2 } equals
new {(string?)Reference1 = s.OverrideReference1 ?? s.Reference1,
(string?)Reference2= s.Reference2 }
代码:
var results = (from d in draft
join s in saved on new {(string?)Reference1 = d.Reference1,(string?)Reference2= d.Reference2 } equals
new {(string?)Reference1 = s.OverrideReference1 ?? s.Reference1,(string?)Reference2= s.Reference2 }
select new Product
{
ProductName = d.ProductName,
Quantity = s.Quantity - d.Quantity,
Reference1 = d.Reference1,
Status = d.Status
}).ToList();