Sunday, March 29, 2015

Trying to find duplicate scores in a list

If you want to find the winners by using LINQ then you have to group by the score. As is now your code groups by whatever Equals means for people, unlikely to be what you want. Also, if the People list isn't already ordered by score you'll need to order the result of GroupBy if you want the winners.


So it should look something like this:



var duplicates = People
.GroupBy(p => p.FinalScore) // group by score
.OrderByDescending(g => g.Key) // order by score
.Take(1) // take the winners group
.SelectMany(g => g); // flatten the result

Take(1).SelectMany() can be replaced with First()/FirstOrDefault() but First() requires the list to be non empty and FirstOrDefault() requires a null check.


Now, this provides an enumerable of winners. To display this in the label you need to obtain a string and Convert.ToString is not what you want. You can use string.Join(", ", duplicates.Select(d => d.Name));


I think it's also worth adding that the code you use now to find a single winner can be modified to find all winners without using LINQ. Given that it took you "sooooooo long to work it out" this may be an useful exercise.


No comments:

Post a Comment