1

I found this posting, regarding selecting a distinct item based on a particular property.

The following will look in my "results" list, group them by ID, and select the first one as the winner.

results.GroupBy(r => r.ID).Select(g => g.First()).ToList();

But, how can I conditionally select the winner?

For example, each result contains a property called Language.Name.

When selecting distinct results, I want to pick the one where result.Language.Name.ToLower() == regionalISOCode as the winner if it exists.

If it does not exist, then the result.Language.Name.ToLower() == "en" should be selected as the winner.

Cœur
  • 37,241
  • 25
  • 195
  • 267
eat-sleep-code
  • 4,753
  • 13
  • 52
  • 98

1 Answers1

6

You just need to change the Select():

results
    .GroupBy(r => r.ID)
    .Select(g => g.FirstOrDefault(r => r.Language.Name.ToLower() == regionalISOCode) ??
                 g.First(r => r.Language.Name.ToLower() == "en"))
    .ToList();
itsme86
  • 19,266
  • 4
  • 41
  • 57