Garrett Daniel DeMeyer
Garrett Daniel DeMeyer

Reputation: 931

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.

Upvotes: 9

Views: 16820

Answers (3)

Michael
Michael

Reputation: 854

This partially answers the question above, but I justed need a really basic solution:

objects.GroupBy(x => x.Id)
       .Select(x => x.First())
       .ToArray();

The key to getting the original object from the GroupBy() is the Select() getting the First() and the ToArray() gets you an array of your objects, not a Linq object.

Upvotes: 2

Andromedary
Andromedary

Reputation: 3548

Something like this should work:

var result =
    objects.GroupBy(x => x.Id).Select(g =>
        g.FirstOrDefault(y => !y.booleanValue) ?? g.First())

This assumes that your objects are of a reference type.

Another possibility might be to use Distinct() with a custom IEqualityComparer<>.

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 148980

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());

Upvotes: 19

Related Questions