解析字符串并创建字典

use*_*827 5 c#

我有以下字符串模式:1:2,2:3.

这就像一个字符串中的数组:
第一个元素是:1:2
第二个元素是:2:3

我想解析它并创建一个字典:

1,2 // 0 element in Dictionary  
2,3 // 1 element in Dictionary  
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

Dictionary<int,int> placesTypes = new Dictionary<int, int>();

foreach (var place in places.Split(','))
{
   var keyValuePair = place.Split(':');
   placesTypes.Add(int.Parse(keyValuePair[0]), int.Parse(keyValuePair[1]));
}
Run Code Online (Sandbox Code Playgroud)

有最好的方法吗?

谢谢.

Dan*_*rth 9

您可以将其更改为:

var d = s.Split(',')
         .Select(x => x.Split(':'))
         .ToDictionary(x => int.Parse(x[0]), x => int.Parse(x[1]));
Run Code Online (Sandbox Code Playgroud)


Nik*_*wal 6

Dictionary<int, int> dict = "1:2,2:3".Split(',')
                           .Select(x => x.Split(':'))
                           .ToDictionary(x => int.Parse(x[0]), 
                                         x => int.Parse(x[1]));
Run Code Online (Sandbox Code Playgroud)