一个简单的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]);