将偶数键和奇值的数组转换成字典的最优雅的方法?

时间:2022-02-09 21:05:46

I have an array that has alternating keys and values because I don't know how to pass a dictionary in a GET in a url for the default binder.

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

the string array comes into the controller ok:

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

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

I need to convert it into a dictionary:

我需要把它转换成一本字典:

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

I tried:

我试着:

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

but that gives an error at runtime. Index not found.

但这在运行时会产生错误。未找到索引。

2 个解决方案

#1


3  

using a for loop

使用一个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]);
}

#2


1  

Simple loop would do (and I would personally do it this way), but if you want to use LINQ you could use Windowed from moreLINQ library. It would looks something like this:

简单的循环就可以了(我个人也是这么做的),但是如果您想使用LINQ,您可以使用来自moreLINQ库的窗口。大概是这样的:

values.Windowed(2).ToDictionary(v => int.Parse(v.First()), v => v.Last());

You could also get away without that with Select+GroupBy:

你也可以不用选择+GroupBy:

values.Select((Value, Index) => { Value, Index })
      .GroupBy(x => x.Index / 2)
      .ToDictionary(g => int.Parse(g.First().Value), g => g.Last().Value);

I wouldn't call it elegant though.

我不认为它是优雅的。

#1


3  

using a for loop

使用一个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]);
}

#2


1  

Simple loop would do (and I would personally do it this way), but if you want to use LINQ you could use Windowed from moreLINQ library. It would looks something like this:

简单的循环就可以了(我个人也是这么做的),但是如果您想使用LINQ,您可以使用来自moreLINQ库的窗口。大概是这样的:

values.Windowed(2).ToDictionary(v => int.Parse(v.First()), v => v.Last());

You could also get away without that with Select+GroupBy:

你也可以不用选择+GroupBy:

values.Select((Value, Index) => { Value, Index })
      .GroupBy(x => x.Index / 2)
      .ToDictionary(g => int.Parse(g.First().Value), g => g.Last().Value);

I wouldn't call it elegant though.

我不认为它是优雅的。