Wednesday, May 16, 2012

parsing string and create Dictionary

I have the following string pattern: 1:2,2:3.



This is like array in one string:

The first element is: 1:2

The second element is: 2:3



I want to parse it and create a dictionary:

1,2 // 0 element in Dictionary

2,3 // 1 element in Dictionary



This is my code:



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]));
}


Is there the best way to do this?



Thanks.





No comments:

Post a Comment