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?
To find the duplicate values only:var duplicates = list. GroupBy(x => x. Key).
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With