将C#字符串数组转换为字典

是否有一种优雅的方式来转换这个字符串数组:

string[] a = new[] {"name", "Fred", "colour", "green", "sport", "tennis"}; 

进入一个字典,使得数组的每两个连续元素成为字典的一个{key,value}对(我的意思是{“name” – >“Fred”,“color” – >“green”,“sport” – > “网球”})?

我可以通过循环轻松完成,但是有更优雅的方式,也许使用LINQ?

这个怎么样 ?

  var q = a.Zip(a.Skip(1), (Key, Value) => new { Key, Value }) .Where((pair,index) => index % 2 == 0) .ToDictionary(pair => pair.Key, pair => pair.Value); 
 var dict = a.Select((s, i) => new { s, i }) .GroupBy(x => xi / 2) .ToDictionary(g => g.First().s, g => g.Last().s); 

因为它是一个数组,我会这样做:

 var result = Enumerable.Range(0,a.Length/2) .ToDictionary(x => a[2 * x], x => a[2 * x + 1]); 

我已经制作了一个类似的方法来处理这种类型的请求。 但由于你的数组包含键和值,我认为你需要先拆分它。

然后你可以使用这样的东西来组合它们

 public static IDictionary ZipMyTwoListToDictionary(IEnumerable listContainingKeys, IEnumerable listContainingValue) { return listContainingValue.Zip(listContainingKeys, (value, key) => new { value, key }).ToDictionary(i => i.key, i => i.value); } 
 a.Select((input, index) = >new {index}) .Where(x=>x.index%2!=0) .ToDictionary(x => a[x.index], x => a[x.index+1]) 

我建议使用for循环,但我已根据您的要求回答..这绝不是整洁/清洁..

 public static IEnumerable EveryOther(this IEnumerable source) { bool shouldReturn = true; foreach (T item in source) { if (shouldReturn) yield return item; shouldReturn = !shouldReturn; } } public static Dictionary MakeDictionary(IEnumerable source) { return source.EveryOther() .Zip(source.Skip(1).EveryOther(), (a, b) => new { Key = a, Value = b }) .ToDictionary(pair => pair.Key, pair => pair.Value); } 

设置方式,并且由于Zip工作方式,如果列表中有奇数个项目,则忽略最后一项,而不是生成某种exception。

注意:从这个答案中得出。

 IEnumerable strArray = new string[] { "name", "Fred", "colour", "green", "sport", "tennis" }; var even = strArray.ToList().Where((c, i) => (i % 2 == 0)).ToList(); var odd = strArray.ToList().Where((c, i) => (i % 2 != 0)).ToList(); Dictionary dict = even.ToDictionary(x => x, x => odd[even.IndexOf(x)]);