LINQ查询找到重复的对象基于多个字段和属性为null [英] Linq query to find duplicate objects based on multiple fields AND property is null

查看:371
本文介绍了LINQ查询找到重复的对象基于多个字段和属性为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于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

这篇关于LINQ查询找到重复的对象基于多个字段和属性为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆