【问题标题】:Using c# Dictionary to group values使用 c# Dictionary 对值进行分组
【发布时间】:2019-12-02 07:23:52
【问题描述】:

我有一个字符序列(例如“}çæø Ñ”),我需要获得一个 char,count 对,其中 char 是 ASCII 字符代码count 是同一字符的连续重复次数。

因此,上述序列将变为:

<125,1>
<135,1>
<145,1>
<32,5>
<155,1>
<32,3>

有没有一种使用字典的快速方法?

我只需要计算相邻字符(见上例中的第 32 个字符)。 我知道字典不能有键重复,所以有没有另一种不涉及字符串的快速方法迭代?我可能要处理很长的字符串,并且迭代需要的时间太长。

【问题讨论】:

标签: c# dictionary char


【解决方案1】:

MoreLinq 库有你需要的方法,见GroupAdjacent

用法:

string source = "}çæø     Ñ   ";
IEnumerable<(char c, int)> groups =
    source.GroupAdjacent(x => x, (c, lst) => (c, lst.Count()));

// Outputs ('}', 1) ('ç', 1) ('æ', 1) ('ø', 1) (' ', 5) ('Ñ', 1) (' ', 3)
Console.WriteLine(string.Join(" ", groups.Select((kv) => $"('{kv.Item1}', {kv.Item2})")));

【讨论】:

    【解决方案2】:

    标准 Linq 不提供 GroupByAdjacent 或类似方法,但我们可以借助简单的 foreach 循环来实现它。请注意,我们不能使用Dictionary&lt;char, int&gt;,因为字典必须具有唯一 Keys(Key == ' ' 不能重复):

      string source = "}çæø     Ñ   ";
    
      // We can't use Dictionary<char, int>
      // Let's put a list instead
      List<KeyValuePair<char, int>> result = new List<KeyValuePair<char, int>>();
    
      foreach (char c in source)
        if (result.Count <= 0 || result[result.Count - 1].Key != c)
          result.Add(new KeyValuePair<char, int>(c, 1));
        else
          result[result.Count - 1] = 
            new KeyValuePair<char, int>(c, result[result.Count - 1].Value + 1);
    

    让我们看看:

      string report = string.Join(Environment.NewLine, result
        .Select(pair => $"<'{pair.Key}' ({(int) pair.Key,3}) : {pair.Value}>"));
    
      Console.Write(report);
    

    结果:(请注意,char 不是一个 Ascii 字符,而是 Unicode)

    <'}' (125) : 1>
    <'ç' (231) : 1>
    <'æ' (230) : 1>
    <'ø' (248) : 1>
    <' ' ( 32) : 5>
    <'Ñ' (209) : 1>
    <' ' ( 32) : 3>
    

    【讨论】:

    • "注意,我们不能使用 Dictionary" 但是我们可以使用LookUp
    • 这将如何工作?我也不熟悉 Lookup...
    • 如果是LookUp&lt;char, int&gt;(或者说,Dictionary&lt;char, int[]&gt;),我们只有&lt;' ', {5, 3}&gt;记录:我们有53后续空格某处,但我们不知道确切的位置(例如,“在 ø 符号之后,我们有 5 空格”)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多