我仍然在c#世界找到了脚,我最近一直在看Linq。我的问题是:
我有一个包含userID和整数值列表(游戏分数)的字典。我想知道是否有可能获得每个用户的整体计数?
var scoreDictionary = new Dictionary<int, List<int>>();
实施例, 键= 1234 值= {23,25,35,13,57,32}
答案 0 :(得分:2)
假设您需要从user-id到
的查找表...用户分数的号:
scoreDictionary.ToDictionary(pair => pair.Key, pair => pair.Value.Count)
...用户分数的总和:
scoreDictionary.ToDictionary(pair => pair.Key, pair => pair.Value.Sum())
顺便说一句,您还可以考虑使用ILookup<,>
界面来表示您在那里的多地图,而不是Dictionary<,>
,其集合为TValue
。
答案 1 :(得分:0)
您可以使用Sum
方法。
不确定要对每个总计做什么。这将输出每个用户的总分:
foreach (var user in scoreDictionary)
{
Console.WriteLine(
"User {0} has a total score of {1}", user.Key, user.Value.Sum());
}
您还可以创建一个新词典来存储值:
var scores = scoreDictionary.ToDictionary(x => x.Key, x => x.Value.Sum());
答案 2 :(得分:0)
怎么样
foreach(var item in scoreDictionary)
{
Console.WriteLine("User " + item.Key " + has a score of " + item.Value.Sum());
}
这会像这样打印
User 1234 has a score of 185
User 5678 has a score of 252
答案 3 :(得分:0)
列表有一个计数属性,所以你可以这样得到给定玩家(其id存储在'playerId')的得分数:
int playerScoreCount = scoreDictionary[playerId].Count;
答案 4 :(得分:0)
您可以尝试以下代码。希望这会有所帮助。
var scores = scoreDictionary.ToDictionary(x => x.Key, x => x.Value.Sum());