Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates of a List, selecting by a property value in C#?

I have a list of objects that I need some duplicates removed from. We consider them duplicates if they have the same Id and prefer the one whose booleanValue is false. Here's what I have so far:

objects.GroupBy(x => x.Id).Select(x => x.Where(y => !y.booleanValue));

I've determined that GroupBy is doing no such grouping, so I don't see if any of the other functions are working. Any ideas on this? Thanks in advance.

like image 347
Garrett Daniel DeMeyer Avatar asked Apr 11 '13 00:04

Garrett Daniel DeMeyer


People also ask

How do I remove duplicates based on condition?

To remove duplicate values, click Data > Data Tools > Remove Duplicates. To highlight unique or duplicate values, use the Conditional Formatting command in the Style group on the Home tab.

How do I remove duplicates from a list in C sharp?

Use the Distinct() method to remove duplicates from a list in C#.

Does converting set to list remove duplicates?

Using set Therefore, converting a list into a set removes the duplicates. Changing the set into a list yields a new list without duplicates. The following example shows how to remove duplicates from the students list using set . Notice that the order of the elements in the list is different from our previous examples.


1 Answers

You can do this:

var results = 
    from x in objects
    group x by x.Id into g
    select g.OrderBy(y => y.booleanValue).First();

For every Id it finds in objects, it will select the first element where booleanValue == false, or the the first one (if none of them have booleanValue == false).

If you prefer fluent syntax:

var results = objects.GroupBy(x => x.Id)
                     .Select(g => g.OrderBy(y => y.booleanValue).First());
like image 79
p.s.w.g Avatar answered Oct 03 '22 17:10

p.s.w.g