【问题标题】:Aggregation using LINQ使用 LINQ 进行聚合
【发布时间】:2019-11-28 09:38:53
【问题描述】:

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

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

【问题讨论】:

  • 只有0s 被分组吗?如果有两个连续的9s,这意味着字典中有一个条目还是两个?

标签: c# linq dictionary group-by


【解决方案1】:

一个简单的for loop(不是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'数字零),见下面的 cmets;如果是你的情况

  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]);

【讨论】:

  • 我希望避免循环,因为我的字符串可能很长。
  • 我会做类似的事情,但你的答案与标题“如何使用 LINQ 做”不匹配。如果我这样回答,我会比我按提交更快地被否决。也许你应该添加一个 linq 版本。
  • @user2729463: 你必须在字符串上循环(显式for或隐式IEnumerator&lt;T&gt;在Linq的情况下)
  • 似乎没有将它们分组。
  • @user2729463:我们不必将所有后续的0 分组然后采取组中的第一项:我们可以采取第一个 0skip 后续 0s
猜你喜欢
  • 2019-02-03
  • 1970-01-01
  • 2012-11-22
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
相关资源
最近更新 更多