从字符串到字典键和值
From string to Dictionary key and value
我有一个值为“13,104,76,73,47,94”的字符串,我想做的是将其转换为字典,以便 13 是键,104 是值,76 是键73 是价值……等等。我会向您展示一些示例代码,但老实说我完全不知道我该怎么做,所以确实有 none 可以展示。
谢谢
基本上,这很简单。
Dictionary<int, string> dictionary = new Dictionary<int, string>();
for (int i = 0; i < numOfStringsYouHave; i+=2) {
dictionary.Add(StringArray[i].ToInt32, StringArray[i+1]);
}
只是伪代码,我没有编译它,但它应该可以正常工作并给你一个想法:
// Your data
string values = "1,10,2,20,3,30";
// Split string by comma
string[] splitted = values.split(',');
// declare a new dictionary
Dictionary<int,int> dict = new Dictionary<int,int>();
// for loop on the splitted data, the counter is increased by 2.
for(int i;i<splitted.Length,i+=2)
{
//Parse the string data as integer and add it to the dictionary.
dict.Add(int.Parse(splitted[i]), int.Parse(splitted[i+1]))
}
我有一个值为“13,104,76,73,47,94”的字符串,我想做的是将其转换为字典,以便 13 是键,104 是值,76 是键73 是价值……等等。我会向您展示一些示例代码,但老实说我完全不知道我该怎么做,所以确实有 none 可以展示。
谢谢
基本上,这很简单。
Dictionary<int, string> dictionary = new Dictionary<int, string>();
for (int i = 0; i < numOfStringsYouHave; i+=2) {
dictionary.Add(StringArray[i].ToInt32, StringArray[i+1]);
}
只是伪代码,我没有编译它,但它应该可以正常工作并给你一个想法:
// Your data
string values = "1,10,2,20,3,30";
// Split string by comma
string[] splitted = values.split(',');
// declare a new dictionary
Dictionary<int,int> dict = new Dictionary<int,int>();
// for loop on the splitted data, the counter is increased by 2.
for(int i;i<splitted.Length,i+=2)
{
//Parse the string data as integer and add it to the dictionary.
dict.Add(int.Parse(splitted[i]), int.Parse(splitted[i+1]))
}