我这里有Python中计数器类的文档。
我在C#中有一个哈希集,它是从C#中的字符串列表生成的。我一直在使用这个代码块来计数项目。
foreach( var item in dict_of_dates.Values)
{
foreach(var item2 in item)
{
if (item2 == set_1.ElementAt(0))
count++;
else if (item2 == set_1.ElementAt(1))
count_1++;
else if (item2 == set_1.ElementAt(2))
count_2++;
else if (item2 == set_1.ElementAt(3))
count_3++;
else if (item2 == set_1.ElementAt(4))
count_4++;
else if (!set_1.Contains(item2))
count_5++;
}
}
这段代码的问题是,如果我不知道集合中的项目数量。它只需要增加if elseif条件的数量,并将计数保存到计数器变量中。我想避免这种情况,因为它通常会使代码变得庞大。我的一般问题是,在C#中是否有一个预构建的计数器类,可能使用lambdas和散列集,或者我必须创建自己的计数器类?
我正在尝试获取一个具有以下输出的集合:
{"a": 20, "b": 30, "c": 40}
这就像我可以循环输出并绘制键和值。
我读过这个问题,它是在F#。
Question 1
有效的解决方案:
var h = dict_of_dates.Values
.SelectMany(x => x)
.GroupBy(s => s)
.ToDictionary(g => g.Key, g => g.Count());
foreach(var item in h)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
1条答案
按热度按时间cxfofazt1#
使用LINQ的方法是:
这将通过按值对列表中的元素进行分组,然后对每个组的元素进行计数,从而创建列表中的元素的直方图。
在行动:Fiddle