Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I replicate this code by using anonymous function (lambda)?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading