C# 数一数
在C#中,我有一个列表,其中包含字符串格式的数字。计算这些数字的最佳方法是什么?例如说我有三倍于数字10 我的意思是,在unix-awk中,你可以说C# 数一数,c#,algorithm,C#,Algorithm,在C#中,我有一个列表,其中包含字符串格式的数字。计算这些数字的最佳方法是什么?例如说我有三倍于数字10 我的意思是,在unix-awk中,你可以说 tempArray["5"] +=1 它类似于KeyValuePair,但它是只读的 有什么快速而聪明的方法吗?(正如digEmAll的回答所指出的,我假设你并不真的在乎它们是数字——这里的一切都假设你想把它们当作字符串来对待。) 最简单的方法是使用LINQ: var dictionary = values.GroupBy(x => x)
tempArray["5"] +=1
它类似于KeyValuePair,但它是只读的
有什么快速而聪明的方法吗?(正如digEmAll的回答所指出的,我假设你并不真的在乎它们是数字——这里的一切都假设你想把它们当作字符串来对待。)
最简单的方法是使用LINQ:
var dictionary = values.GroupBy(x => x)
.ToDictionary(group => group.Key, group => group.Count());
您可以自己创建字典,如下所示:
var map = new Dictionary<string, int>();
foreach (string number in list)
{
int count;
// You'd normally want to check the return value, but in this case you
// don't care.
map.TryGetValue(number, out count);
map[number] = count + 1;
}
使用LINQ非常简单:
var occurrenciesByNumber = list.GroupBy(x => x)
.ToDictionary(x => x.Key, x.Count());
当然,作为以字符串表示的数字,此代码确实可以区分例如“001”
和“1”
之间的差异,即使概念上是相同的数字
要计算具有相同值的数字,可以执行以下操作,例如:
var occurrenciesByNumber = list.GroupBy(x => int.Parse(x))
.ToDictionary(x => x.Key, x.Count());
var occurrenciesByNumber = list.GroupBy(x => x)
.ToDictionary(x => x.Key, x.Count());
var occurrenciesByNumber = list.GroupBy(x => int.Parse(x))
.ToDictionary(x => x.Key, x.Count());