【问题标题】:From string to Dictionary key and value [duplicate]从字符串到字典键和值[重复]
【发布时间】:2015-05-17 14:27:15
【问题描述】:

我有一串值“13,104,76,73,47,94”我想做的是将其转换为字典,以便 13 是键,104 是值,76 是键,73是价值..等等。我会向您展示一些示例代码,但老实说,我完全不知道如何做到这一点,所以真的没有什么可以展示的。

谢谢

【问题讨论】:

  • 调用Split()然后写一个循环。
  • ... or this or this or this or this or this ...
  • ... 或this - 这也已在MSDN forums 上讨论过。我通过简单地搜索 c# split string key value 找到了所有这些。
  • 哦,dayum 并没有考虑用谷歌搜索这些关键字,我用谷歌搜索了 convert array to dictionary key and value
  • @sean:您需要考虑这样做涉及哪些步骤。

标签: c#-4.0


【解决方案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]))
}

【讨论】:

    【解决方案2】:

    基本上,这很简单。

    Dictionary<int, string> dictionary = new Dictionary<int, string>(); for (int i = 0; i < numOfStringsYouHave; i+=2) { dictionary.Add(StringArray[i].ToInt32, StringArray[i+1]); }

    Converting String

    Dictionary docs C#

    【讨论】:

    • 实际上,Add 不会覆盖以前存在的值,如果键已经存在,它会抛出一个ArgumentException
    • 此外,“您可能想要的是一个哈希表”这句话没有多大意义 - Dictionary&lt;TKey, TValue&gt; 一个哈希表(参见您链接到的文档:“Dictionary&lt;TKey, TValue&gt; 类被实现为哈希表。”)。为每个键获取多个值需要做的是使用集合类型作为值,尽管我认为已经有很多关于 SO 的问题讨论了这一点。
    • 感谢您的澄清。
    • 忘了说在调用这个函数之前字典会被清除所以不用担心覆盖任何东西
    • @sean:如果您的字符串中有重复的键,则会发生覆盖(或者更确切地说是异常),无论字典的先前内容是否被清除。
    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2016-06-24
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    相关资源
    最近更新 更多