I have a nested dictionary which looks like this:
Dictionary<string, Dictionary<string, int>> users = new Dictionary<string, Dictionary<string, int>>();
The first string is the name of the user, the second is the contest he is taking part in and the int is his score. One user can take part in multiple contests.
My task is to find the user with the highest score by adding all the points he has. For now I used this code :
foreach (var user in users)
{
bestUsers.Add(user.Key, 0);
foreach (var contest in user.Value)
{
bestUsers[user.Key] += contest.Value;
}
}
I want to know how to do it by using anonymous function looking something like this :
KeyValuePair<string, int> bestUser = users.OrderBy(x => x.Value.Sum());
>Solution :
Instead of a nested dictionary, you can create a class that represents the results of the User:
public class UserGameResults
{
public string Name { get; set; } // the name of the user
public int TotalScore { get => GameResults.Select(x => x.Value).Sum(); } // total score of all games, will be calculated every time the property is accessed
public Dictionary<string,int> GameResults { get; set; } = new Dictionary<string,int>(); // key is the name of the game, value is the score
}
If you use a Dictionary<string,UserGameResults>, you will get your result more easily:
var bestResult = users.OrderByDescending(x => x.Value.TotalScore).FirstOrDefault();
Moreover, a Dictionary<string,UserGameResults>tells you much more about the meaning of the data than the Dictionary<string,Dictionary<string,int>>.