将C#字符串数组转换为字典 [英] Convert a C# string array to a dictionary

查看:140
本文介绍了将C#字符串数组转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种优雅的方式来转换此字符串数组:

Is there an elegant way of converting this string array:

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

放入字典,使数组的每两个连续元素成为字典的一对{key,value}(我的意思是{"name"->"Fred","colour"->"green","sport->"网球})?

into a Dictionary such that every two successive elements of the array become one {key, value} pair of the dictionary (I mean {"name" -> "Fred", "colour" -> "green", "sport" -> "tennis"})?

我可以轻松地通过循环来完成此操作,但是有没有更优雅的方法,也许可以使用LINQ?

I can do it easily with a loop, but is there a more elegant way, perhaps using 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);

这篇关于将C#字符串数组转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆