字符串拆分:未找到密钥异常

时间:2014-04-05 15:11:48

标签: c# linq dictionary

我有一个由':Item:'分隔的字符串消息我希望使用唯一键将项目放在':Item:'旁边的字典中

    string input = "aaaaa:Item:ID1222222:Item:ID3444444:Item:ID4555555";
    var response = new Dictionary<string, string>();
    string[] values = input.Split(':');

       for (int i = 0; i < values.Length; i++)
       {
         if (!values[i].Contains("Item"))
           {
           // use the id as a unique key 
              response.Add(values[i].Substring(1, 3), values[i]);

          }
           Console.WriteLine(response["ID1"]);
           Console.ReadLine();
       }

但是这给了我一个未发现的密钥异常,因为值[0]没有我用作密钥的ID。 如何跳过集合中的第一个元素?还是有另一种有效的方法吗?

修改 我想在字典中加入的是:

  key = "AA", value = "aaaaa"
  key = "ID1",    value = "ID1222222"
  key = "ID3"      valeu ="ID3444444"
 key = "ID4"      value "ID4555555"

感谢

2 个答案:

答案 0 :(得分:1)

您可以使用LINQ来获得预期的输出:

var dictionary = input.Split(':')
                 .Where(x => !x.Contains("Item"))
                 .ToDictionary(x => x.Substring(0, 3), x => x);

LINQPad中的结果:

enter image description here

注意:如果您的Substring包含少于三个字符,key可能会抛出异常,为了解决此问题,您可以执行以下操作:

var dictionary = input.Split(':')
             .Where(x => !x.Contains("Item"))
             .ToDictionary(x => x.Length >=3 ? x.Substring(0, 3) : x, x => x);

答案 1 :(得分:0)

string input = "aaaaa:Item:ID1222222:Item:ID3444444:Item:ID4555555";
            var response = new Dictionary<string, string>();
            string[] values = input.Split(':');

            for (int i = 1; i < values.Length; i++)
            {
                if (!values[i].Contains("Item"))
                {
                    // use the id as a unique key 
                    response.Add(values[i].Substring(0, 3), values[i]);

                }
            }

            for (int i = 0; i < response.Count; i++)
            {
                if (response.ContainsKey("ID1"))
                {
                    Console.WriteLine(response["ID1"]);
                    Console.ReadLine();
                }
            }