如何使用匿名函数(lambda)复制此代码?

Yan*_*iev 2 .net c# lambda dictionary

我有一个嵌套字典,如下所示:

Dictionary<string, Dictionary<string, int>> users = new Dictionary<string, Dictionary<string, int>>();
Run Code Online (Sandbox Code Playgroud)

第一个字符串是用户的姓名,第二个字符串是他正在参加的比赛,int 是他的分数。一名用户可以参加多项竞赛。

我的任务是通过添加所有得分来找到得分最高的用户。现在我使用这段代码:

foreach (var user in users)
{
    bestUsers.Add(user.Key, 0);
    foreach (var contest in user.Value)
    {
        bestUsers[user.Key] += contest.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用匿名函数来做到这一点,如下所示:

KeyValuePair<string, int> bestUser = users.OrderBy(x => x.Value.Sum());
Run Code Online (Sandbox Code Playgroud)

Som*_*ody 5

您可以创建一个表示用户结果的类,而不是嵌套字典:

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
}
Run Code Online (Sandbox Code Playgroud)

如果您使用 a Dictionary<string,UserGameResults>,您将更容易获得结果:

var bestResult = users.OrderByDescending(x => x.Value.TotalScore).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

此外,aDictionary<string,UserGameResults>比 告诉您更多有关数据含义的信息Dictionary<string,Dictionary<string,int>>