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
  • 34,719
  • 24
  • 185
  • 251
eat-sleep-code
  • 4,611
  • 12
  • 48
  • 93

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
  • 18,916
  • 4
  • 39
  • 54