c# - 所有值的计数均为零的频率表

标签 c# .net linq

<分区>

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;
    }
  }
}

最佳答案

如果您没有以某种方式指定所有可能的键值,您的字典将不会包含此类键的条目。

与其存储零计数,不如使用

Dictionary.TryGetValue(...)

在尝试访问之前测试 key 是否存在。如果 TryGetValue 返回 false,只需返回 0。

您可以轻松地将其包装在扩展方法中(而不是创建自定义集合)。

static public class Extensions
{
    static public int GetFrequencyCount<K>(this Dictionary<K, int> counts, K value)
    {
        int result;
        if (counts.TryGetValue(value, out result))
        {
            return result;
        }
        else return 0;
    }
}

用法:

Dictionary<char, int> counts = new Dictionary<char, int>();
counts.Add('1', 42);
int count = counts.GetFrequencyCount<char>('1');

关于c# - 所有值的计数均为零的频率表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368180/

相关文章:

c# - Microsoft Access 2010 .accdb 的 SQL 连接字符串

linq - EF LINQ 选择 Id 位于列表中的实体

c# - DevExpress MVC GridView BindToLINQ() 选择了太多数据

.net - 在没有 .NET Framework 4 的机器上安装 WPF 应用程序

c# - 缺少程序集时,.NET 应用程序静默无法启动

c# - 使用 LINQ 连接两个表,同时还从第二个表返回空记录

c# - 需要帮助合并两个 LINQ 语句

c# - 从无序列表中按值获取有序组列表的最佳方法

c# - 启动时未调用 ValueConverter

C# 应用程序需要在 Citrix 环境中引用远程工作站