我有一個嵌套的字典,它看起來像這樣:
Dictionary<string, Dictionary<string, int>> users = new Dictionary<string, Dictionary<string, int>>();
第一個字串是用戶的名字,第二個是他參加的比賽,int 是他的分數。一個用戶可以參加多場比賽。
我的任務是通過添加他擁有的所有分數來找到得分最高的用戶。現在我使用了這個代碼:
foreach (var user in users)
{
bestUsers.Add(user.Key, 0);
foreach (var contest in user.Value)
{
bestUsers[user.Key] = contest.Value;
}
}
我想知道如何通過使用看起來像這樣的匿名函式來做到這一點:
KeyValuePair<string, int> bestUser = users.OrderBy(x => x.Value.Sum());
uj5u.com熱心網友回復:
您可以創建一個表示用戶結果的類,而不是嵌套字典:
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
}
如果您使用 a Dictionary<string,UserGameResults>,您將更容易獲得結果:
var bestResult = users.OrderByDescending(x => x.Value.TotalScore).FirstOrDefault();
此外, aDictionary<string,UserGameResults>比Dictionary<string,Dictionary<string,int>>.
uj5u.com熱心網友回復:
對于代碼重構以使用 linq 來獲取字典而不是 2 個 foreach 回圈,您可以使用以下內容:
users.ToDictionary(u => u.Key, u => u.Value.Select(c => c.Value).Sum());
或者我認為 Sum 使用了一個選擇器 lambda
users.ToDictionary(u => u.Key, u => u.Value.Sum(c => c.Value));
應該有效
uj5u.com熱心網友回復:
試試這個
var dict = new Dictionary<string, Dictionary<string, int>> {
{ "name1", new Dictionary<string, int>{ { "A", 2 }, {"B", 3 }}},
{ "name2", new Dictionary<string, int>{ { "C", 4 }, {"D", 5 }}}
};
var scores = dict.Select(d => new { name = d.Key, score = d.Value.Select(x => x.Value).Sum() } )
.ToList().OrderByDescending (d =>d.score );
分數
name2 9
name1 5
uj5u.com熱心網友回復:
您可以使用Dictionary<TKey,TValue>,當你需要存盤值關聯給他們一些獨特的按鍵,并且通過該鍵訪問它們方便你。
我不知道你為什么在這里使用字典。我認為您的用戶名不能是唯一的。因此,如果用戶名不是唯一的,那么您如何將所有用戶存盤在字典中。我認為你應該使用串列而不是字典。
Dictionary<string, Dictionary<string, int>> users = new Dictionary<string, Dictionary<string, int>>()
{
{ "A", new Dictionary<string, int>(){
{"sub1", 10},
{"sub2", 20},
{"sub3", 30}
}
},
{ "B", new Dictionary<string, int>(){
{"sub1", 10},
{"sub2", 40},
{"sub3", 30}
}
}
};
var result = users.OrderBy(x => x.Key).ToDictionary(m => m.Key, m => m.Value.Sum(k => k.Value));
Dictionary 速度非常快,優化得很好,在大多數情況下都能提供您需要的性能。但在大多數情況下,這并不重要,鍵值對鏈表的性能也足夠了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387473.html
上一篇:如何在資料庫中找到真值?
下一篇:如何從字典訪問其他方法?
