Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find duplicate items based on multiple values using LINQ?

Suppose I have the following class:

public class Test{
    public string Length { get; set; }
    public string Width { get; set; }
    public string Height { get; set; }
    public int Count { get; set; }
    public string Label { get; set; }
}

And I would like to find items that have the same value for length and label and counting how many there are for each. So far my code looks like:

var dups = testlist.GroupBy(i => new { i.Length, i.Label })
                   .Where(g => g.Count() >= 1)
                   .Select(g => new { Length = g.Key.Length, Label = g.Key.Label, 
                                      Count = g.Count() });

But the problem is, the objects in var no longer have the width or height property (they don't exist in g.Key). Is there anyway to find duplicates based on two properties while saving other properties in the result?

like image 853
Tony Avatar asked Oct 23 '12 14:10

Tony


People also ask

How do I find duplicate records in Linq?

To find the duplicate values only:var duplicates = list. GroupBy(x => x. Key).

How do I remove duplicate values in Linq?

We can remove all duplicates like this by using GroupBy and Select methods provided by LINQ . First, we group our list so that we will create groups for each name in the List. Then we use Select to only select the first objects in each group. This will result in the removal of the duplicates.

Does Linq Union remove duplicates?

Linq, acts upon 2 collections. It returns a new collection that contains the elements that are found. Union removes duplicates. So this method can be thought of as two actions: it combines the two collections and then uses Distinct() on them, removing duplicate elements.

Can a List have duplicate values in C#?

A List may have duplicate elements—to eliminate these, we call Distinct(). We can use a method like ToList() to go from an IEnumerable to a List again. Distinct example. This program uses the System.


1 Answers

After this

testList
  .GroupBy(i => new { i.Length, i.Label })
  .Where(g => g.Count() >= 1)

you effectively have an IEnumerable<IEnumerable<Test>>. That's a list of lists of dupes. What more do you want?

like image 94
spender Avatar answered Sep 21 '22 06:09

spender