Skip to main content
The 2024 Developer Survey results are live! See the results
added 11 characters in body
Source Link
Peter Mortensen
  • 31.4k
  • 22
  • 109
  • 132
string input = "key1:value key2:value key3:value";
Dictionary<string, string> dic = input.Split(' ').Select(x => x.Split(':')).ToDictionary(x => x[0], x => x[1]);

FirstThe first will produce an array:

"key:value", "key:value"

Then an array of arrays:

{ "key", "value" }, { "key", "value" }

And then a dictionary:

"key" => "value", "key" => "value"

Note, that Dictionary<K,V> doesn't allow duplicated keys, it will raise an exception in such a case. If such a scenario is possible, use ToLookup().

string input = "key1:value key2:value key3:value";
Dictionary<string, string> dic = input.Split(' ').Select(x => x.Split(':')).ToDictionary(x => x[0], x => x[1]);

First will produce an array:

"key:value", "key:value"

Then an array of arrays:

{ "key", "value" }, { "key", "value" }

And then a dictionary:

"key" => "value", "key" => "value"

Note, that Dictionary<K,V> doesn't allow duplicated keys, it will raise an exception in such case. If such scenario is possible, use ToLookup()

string input = "key1:value key2:value key3:value";
Dictionary<string, string> dic = input.Split(' ').Select(x => x.Split(':')).ToDictionary(x => x[0], x => x[1]);

The first will produce an array:

"key:value", "key:value"

Then an array of arrays:

{ "key", "value" }, { "key", "value" }

And then a dictionary:

"key" => "value", "key" => "value"

Note, that Dictionary<K,V> doesn't allow duplicated keys, it will raise an exception in such a case. If such a scenario is possible, use ToLookup().

Source Link
abatishchev
  • 99.6k
  • 88
  • 300
  • 439

string input = "key1:value key2:value key3:value";
Dictionary<string, string> dic = input.Split(' ').Select(x => x.Split(':')).ToDictionary(x => x[0], x => x[1]);

First will produce an array:

"key:value", "key:value"

Then an array of arrays:

{ "key", "value" }, { "key", "value" }

And then a dictionary:

"key" => "value", "key" => "value"

Note, that Dictionary<K,V> doesn't allow duplicated keys, it will raise an exception in such case. If such scenario is possible, use ToLookup()