<分区>
Possible Duplicate:
Dictionary returning a default value if the key does not exist
我有一个只包含数字的字符串。我有兴趣生成数字的频率表。这是一个示例字符串:
var candidate = "424256";
此代码有效,但如果我查找不在字符串中的数字,它会抛出 KeyNotFound
异常:
var frequencyTable = candidate
.GroupBy(x => x)
.ToDictionary(g => g.Key, g => g.Count());
产生:
Key Count
4 2
2 2
5 1
6 1
所以,我使用了这段有效的代码:
var frequencyTable = (candidate + "1234567890")
.GroupBy(x => x)
.ToDictionary(g => g.Key, g => g.Count() - 1);
但是,在其他用例中,我不想指定所有可能的键值。
是否有一种优雅的方法可以将 0 计数记录插入 frequencyTable
字典,而无需借助于创建具有这种行为的自定义集合,例如这个?
public class FrequencyTable<K> : Dictionary<K, int>
{
public FrequencyTable(IDictionary<K, int> dictionary)
: base(dictionary)
{ }
public new int this[K index]
{
get
{
if (ContainsKey(index))
return base[index];
return 0;
}
}
}