Parsing a string and creating a dictionary

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

It looks like an array in one line:
First element: 1:2
Second element:2:3

I want to analyze 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 a better way to do this?

Thank.

+3
source share
5 answers

You can change it to this:

var d = s.Split(',')
         .Select(x => x.Split(':'))
         .ToDictionary(x => int.Parse(x[0]), x => int.Parse(x[1]));
+8
source
Dictionary<int, int> dict = "1:2,2:3".Split(',')
                           .Select(x => x.Split(':'))
                           .ToDictionary(x => int.Parse(x[0]), 
                                         x => int.Parse(x[1]));
+6
source
var result = input.Split(new[]{','})
    .Select(s => s.Split(new[]{':'})) 
    .ToDictionary(k => int.Parse(k[0]), v=> int.Parse(v[1]));

: http://rextester.com/GTKO60478

+1

# >= 3.5, ToDictionary LINQ - :

var dictionary = places.Split(',')
                       .Select(place => place.Split(':'))
                       .ToDictionary(keyValue => int.Parse(keyValue[0]), keyValue => int.Parse(keyValue[1]));

:

public static Dictionary<string, string> ToDictionary(string value, char pairSeperator, char valueSeperator) 
{
    Dictionary<int, int> dictionary = new Dictionary<int, int>();
    foreach (string pair in value.Split(pairSeperator))
    {
        string[] keyValue = pair.Split(valueSeperator);
        dictionary.Add(keyValue[0], keyValue[1]);
    }

    return dictionary;
}
+1

, MoreLinq. Batch

 Dictionary<int, int> dict = places.Split(',', ':').Batch(2).Select(x=>x.ToArray()).ToDictionary(x=>int.Parse(x[0]),x=>int.Parse(x[1]));
0

All Articles