My solution:
var dic = new Dictionary<Int32, Int32>();
var ids = new List<int> { 1, 2, 3, 1, 2 };
foreach (var id in ids)
{
if (dic.ContainsKey(id))
{
dic[id]++;
} else {
dic[id] = 1;
}
}
سؤال
Let's say we have a dictionary like this:
var dic = new Dictionary<Int32, Int32>();
Whereas the key is the ID and the value is the count. Now we want to add a new key. This works perfectly fine with the following line:
dic[1] = 1; //adding ID 1, Count 1 to the current Dictionary
Assuming we have a list of integer with the following values:
var ids = new List<int> {1, 2, 3 , 1, 2};
Where we would like to get a dictionary with the following content:
[1, 2] ==> (ID 1, Count 2)
[2, 2] ==> (ID 2, Count 2)
[3, 1] ==> (ID 3, Count 1)
The obvious solution would be:
foreach (var id in ids)
{
dic[id]++;
}
But this is throwing a KeyNotFoundException
. So obviously the operator +=
is not supported for dictionaries.
I already attached an answer to this problem. Is there any better way of how to achieve this?
المحلول 2
My solution:
var dic = new Dictionary<Int32, Int32>();
var ids = new List<int> { 1, 2, 3, 1, 2 };
foreach (var id in ids)
{
if (dic.ContainsKey(id))
{
dic[id]++;
} else {
dic[id] = 1;
}
}
نصائح أخرى
You can use LINQ for simpler:
var dic = ids.GroupBy(id => id)
.ToDictionary(g => g.Key, g => g.Count());