使用LINQ进行聚合

时间:2019-11-28 09:38:53

标签: c# linq dictionary group-by

我有一个string个字符(例如A0009B80000J31500435)。有没有一种创建LINQ字典的方法,该字典将0分组并且仅显示一个条目?我需要的输出如下:

format: <index, character>
<0,A>
<1,0>
<4,9>
<5,B>
<6,8>
<7,0>
<11,J>
...

1 个答案:

答案 0 :(得分:1)

一个简单的for 循环(不是 Linq )应该可以做到:

  string source = "A0009B80000J31500435";

  Dictionary<int, char> result = new Dictionary<int, char>();

  for (int i = 0; i < source.Length; ++i)
    if (i == 0 || source[i] != '0' || source[i - 1] != '0')
      result.Add(i, source[i]);

让我们看看:

  Console.Write(string.Join(Environment.NewLine, result));     

结果:

[0, A]
[1, 0]
[4, 9]
[5, B]
[6, 8]
[7, 0]
[11, J]
[12, 3]
[13, 1]
[14, 5]
[15, 0]
[17, 4]
[18, 3]
[19, 5]

编辑:从技术上讲,我们可以在此处创建 Linq 查询,例如

Dictionary<int, char> result = Enumerable
  .Range(0, source.Length)
  .Where(i => i == 0 || source[i] != '0' || source[i - 1] != '0')
  .ToDictionary(i => i, i => source[i]);

我怀疑这是否是更好的代码。

编辑2:似乎您想压缩\0字符)而不是'0'数字零),请参见下面的注释;如果是您的情况

  string source = "A\0\0\09B8\0\0\0\0J315\0\0435";

  Dictionary<int, char> result = new Dictionary<int, char>();

  for (int i = 0; i < source.Length; ++i)
    if (i == 0 || source[i] != '\0' || source[i - 1] != '\0')
      result.Add(i, source[i]);