将偶数键和奇数值数组转换为字典的最优雅方法是什么?

时间:2017-03-23 20:09:27

标签: c# arrays

我有一个具有交替键和值的数组,因为我不知道如何在默认绑定器的URL中传递GET中的字典。

字符串数组进入控制器ok:

string[] values = new string[] {"123", "Pie", "456", "Cake"};

我需要将其转换为字典:

Dictionary<int,string> Deserts = new     Dictionary<int,string>() { {123, "Pie"}, {456, "Cake"} };

我试过了:

values.ToDictionary(v => int.Parse(v), v => values.IndexOf(v) + 1);

但是在运行时会出错。索引未找到。

2 个答案:

答案 0 :(得分:3)

使用for循环

var deserts = new Dictionary<int,string>();
for (var i = 0; i < values.Length; i += 2) {
    deserts.Add(int.Parse(values[i]), values[i+1]);
}

答案 1 :(得分:1)

简单循环可以做(我个人会这样做)但是如果你想使用LINQ,你可以使用Windowed库中的moreLINQ。它看起来像这样:

Writing these ints to file
1 4 5 6 2 4 10 6 5 5 
Unsorted ints found in random file:
0 0 0 0 0 0 0 0 0 5

如果没有values.Windowed(2).ToDictionary(v => int.Parse(v.First()), v => v.Last()); + Select

,你也可以逃脱
GroupBy

我不会称之为优雅。