Linq查询基于多个字段AND属性查找重复对象为空

我试图找到基于2个字段的重复对象,但仅限于第3个字段也为空的情况

ItemNumber, Name, Pricebook, Parent Item1, A, B,  Item2, A, B, Item1 Item3, A, B,  Item4, A, B, Item1 Item5, A, B, Item2 

所以在上面的列表中,只有2个重复的项目实际上是Item1和Item3

 var duplicateItemsList = from i in items group i by new { i.ItemNumber, i.Pricebook, i.Parent } into d where d.Count() > 1 select new { ItemNumber = d.Key.ItemNumber, Pricebook = d.Key.Pricebook, Parent = d.Key.Parent, Count = d.Count() }; 

我遇到的麻烦是检查Linq查询中的空字段值。

在上面的Linq查询之后,我只想得到一个包含重复的ItemNumber和Pricebook字段值的列表。

我不认为你在结果和groping键中需要Parent属性,因为它将具有null值。 如果匿名对象与已分配属性的名称相同,则无需为匿名对象指定属性名称。

 var duplicateItemsList = from i in items where i.Parent == null group i by new { i.Name, i.Pricebook } into d where d.Count() > 1 select new { d.Key.Name, d.Key.Pricebook, Count = d.Count() }; 

您还可以引入新的范围变量来存储组中的项目数。 然后项目计数只计算一次:

 var duplicateItemsList = from i in items where i.Parent == null group i by new { i.Name, i.Pricebook } into d let groupItemsCount = d.Count() where groupItemsCount > 1 select new { d.Key.Name, d.Key.Pricebook, Count = groupItemsCount }; 

更新为@Blachshma指出,您按ItemNumber而不是Name进行分组

 var duplicateItemsList = from i in items where i.Parent == null group i by new { i.ItemNumber, i.Pricebook, i.Parent } into d where d.Count() > 1 select new { ItemNumber = d.Key.ItemNumber, Pricebook = d.Key.Pricebook, Parent = d.Key.Parent, Count = d.Count() }; 

您可以在分组之前仅过滤空项目,并使用其他where子句进行重复检查。