如何将String []转换为IDictionary& lt; String,String& gt ;? [英] How to convert a String[] to an IDictionary<String, String>?
本文介绍了如何将String []转换为IDictionary& lt; String,String& gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将String[]
转换为IDictionary<String, String>
?
索引0、2、4,...处的值应为键,因此索引1、3、5,...处的值应为键.
The values at the indices 0,2,4,... shall be keys, and consequently values at the indices 1,3,5,... shall be values.
示例:
new[] { "^BI", "connectORCL", "^CR", "connectCR" }
=>
new Dictionary<String, String> {{"^BI", "connectORCL"}, {"^CR", "connectCR"}};
推荐答案
Dictionary<string,string> ArrayToDict(string[] arr)
{
if(arr.Length%2!=0)
throw new ArgumentException("Array doesn't contain an even number of entries");
Dictionary<string,string> dict=new Dictionary<string,string>();
for(int i=0;i<arr.Length/2;i++)
{
string key=arr[2*i];
string value=arr[2*i+1];
dict.Add(key,value);
}
return dict;
}
这篇关于如何将String []转换为IDictionary& lt; String,String& gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文