Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing string and create Dictionary

Tags:

c#

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.

like image 304
user1260827 Avatar asked May 15 '12 07:05

user1260827


People also ask

How do you create a dictionary from a string?

Method 1: Splitting a string to generate key:value pair of the dictionary In this approach, the given string will be analysed and with the use of split() method, the string will be split in such a way that it generates the key:value pair for the creation of a dictionary.

Can we convert string to dictionary in Python?

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.

Can we use string as key in dictionary?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key.


2 Answers

You could change it to this:

var d = s.Split(',')
         .Select(x => x.Split(':'))
         .ToDictionary(x => int.Parse(x[0]), x => int.Parse(x[1]));
like image 86
Daniel Hilgarth Avatar answered Sep 18 '22 03:09

Daniel Hilgarth


Dictionary<int, int> dict = "1:2,2:3".Split(',')
                           .Select(x => x.Split(':'))
                           .ToDictionary(x => int.Parse(x[0]), 
                                         x => int.Parse(x[1]));
like image 34
Nikhil Agrawal Avatar answered Sep 19 '22 03:09

Nikhil Agrawal