我有一个产品列表(草案),需要与数据库(已保存)进行匹配并进行一些计算。当我们检索或创建时,它们是相同的对象。如果我将Reference1 (draft)匹配到Reference1 (saved),将Reference2(draft)匹配到Reference2(saved),则一切顺利,但是它们修改了数据库表,并且还必须修改Object,其中,它们可以通过使用overriderreference1字段覆盖Reference1值。overriderreference1是在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();
列名必须设置相同,您的问题是当字符串为空时使用"OverrideReference1"此属性。
本行问题:
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();