结果字符串包含输入字符串:1 2 3 a b c
预期的操作:
1 a
2 b
3 c
我尝试了什么:
resultKV=result.Split('\t');
foreach (string KV in resultKV)
{
Console.WriteLine(KV);
}
答案 0 :(得分:1)
var parts = "1 2 3 a b c".Split();
var dict = parts.Select((s, inx) => new { s = s, inx = inx })
.GroupBy(x => x.inx % (parts.Length / 2))
.ToDictionary(x => x.First().s, x => x.Last().s);
使用副作用,可以缩短
var parts = "1 2 3 a b c".Split();
int inx = 0;
var dict = parts.GroupBy(x => inx++ % (parts.Length / 2))
.ToDictionary(x => x.First(), x => x.Last());
答案 1 :(得分:0)
string input = "1 2 3 a b c";
var parts = input.Split(' ');
if (parts.Length % 2 == 0)
{
var d = new Dictionary<string, string>();
var halfLength = parts.Length / 2;
for (int i = 0; i < halfLength; i++)
{
d[parts[i]] = parts[halfLength + i];
}
// at this stage the dictionary will contain the desired result
}
else
{
Console.WriteLine("Must have a pair number to build the dictionary");
}
答案 2 :(得分:0)
拆分会导致多个项目吗?换句话说:它是正确的逃脱序列吗? 如果是这样,也许你可以做任何事情:
int l = resultKV.lenght/2;
if(l % 2 == 0)
for(int i = 0; i < l; i++){
Console.WriteLine(resultKV[i]); Console.WriteLine(resultKV[i+l]);
}
(未经测试)