LINQ查询找到重复的对象基于多个字段和属性为null多个、字段、属性、对象

由网友(失夜 ?Sakitama)分享简介:我想基于2场,但只有在第3场也是空I am trying to locate duplicate objects based on 2 fields but ONLY where a 3rd field is also nullItemNumber, Name, Pricebook, ParentItem1, A...

我想基于2场,但只有在第3场也是空

I am trying to locate duplicate objects based on 2 fields but ONLY where a 3rd field is also null

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

所以在上面的列表中只有2个重复的项目是有效项目1和项目3

So in the above list the only 2 duplicate items are effectively Item1 and 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查询空字段值。

The trouble I am having is working the check for the null field value in the Linq query.

在上面的LINQ查询我只是想结束与含重复ItemNumber和价目表字段值的列表。

After the above Linq query I just want to end up with a list containing the duplicated ItemNumber and Pricebook field values.

推荐答案

我不认为你需要的结果,并在摸索的关键,因为它将有物业值。你也并不需要指定属性名匿名对象,如果是一样的分配属性的名称。

I don't think you need Parent property in result and in groping key, because it will have null value. Also you don't need to specify property name for anonymous object if it is same as name of assigned property.

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()
               };

你也可以引入新的范围变量存放物品的组数。然后,项目计数将只计算一次:

Also you can introduce new range variable to store items count in group. Then items count will be calculated only once:

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而不是名称分组

UPDATE as @Blachshma pointed, you have grouping by ItemNumber instead of Name

阅读全文

相关推荐

最新文章