Reputation: 77
I'm still finding my feet in the c# world and I've recently been looking at Linq. My question is:
I have a dictionary which holds a userID and a list of integer values (game scores). I was wondering if it would be possible to get the overall count for each user?
var scoreDictionary = new Dictionary<int, List<int>>();
Example, Key = 1234 Value = {23,25,35,13,57,32}
Upvotes: 2
Views: 904
Reputation: 45
You can try the below code .Hope this will help .
var scores = scoreDictionary.ToDictionary(x => x.Key, x => x.Value.Sum());
Upvotes: 0
Reputation: 48568
how about
foreach(var item in scoreDictionary)
{
Console.WriteLine("User " + item.Key " + has a score of " + item.Value.Sum());
}
This would print like this
User 1234 has a score of 185
User 5678 has a score of 252
Upvotes: 0
Reputation: 3
List has a count property, so you can get the number of scores for a given player (whose id is stored in 'playerId') this way:
int playerScoreCount = scoreDictionary[playerId].Count;
Upvotes: 0
Reputation: 113412
Assuming you want a lookup table from the user-id to
...the number of scores for the user:
scoreDictionary.ToDictionary(pair => pair.Key, pair => pair.Value.Count)
...the sum of scores for the user:
scoreDictionary.ToDictionary(pair => pair.Key, pair => pair.Value.Sum())
By the way, you may also consider using the ILookup<,>
interface to represent the multi-map you have there instead of a Dictionary<,>
with a collection as TValue
.
Upvotes: 2
Reputation: 66449
You can use the Sum
method.
Not sure what you want to do with each total. This will output each user's total score:
foreach (var user in scoreDictionary)
{
Console.WriteLine(
"User {0} has a total score of {1}", user.Key, user.Value.Sum());
}
You could also create a new dictionary to store the values in:
var scores = scoreDictionary.ToDictionary(x => x.Key, x => x.Value.Sum());
Upvotes: 0