Linq query to find duplicate objects based on multiple fields AND property is null

.net, c#, linq

Solution

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

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

Problem

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 ``` 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() }; ``` The trouble I am having is working the check for the null field value in the Linq query. After the above Linq query I just want to end up with a list containing the duplicated ItemNumber and Pricebook field values.

Original source