I'm not completely clear on lambda expressions and I'm trying to use them to convert the following string into a dictionary where the item before the equals sign is the key, and the item after the equals sign is the value.
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string stringOfKeyValuePairs = "Item1=value1 Item2=value2 Item3=value3 Item4=value4"
Is there a way to split the string and use the ToDictionary() method to get the results I want?
Thank you
Edit: I made the string simpler as I can already parse the string down to what I want and the complex version adds no value to the information I am seeking.
CodePudding user response:
If you are keen on doing this in LINQ, you can do a couple of Splits and a ToDictionary, but it feels pretty fragile. I don't know if there will never be spaces, if you will always have unique Keys, etc. If that's not an issue, something like this:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string stringOfKeyValuePairs = "Item1=value1 Item2=value2 Item3=value3 Item4=value4";
var myDictionary = stringOfKeyValuePairs.Split(' ')
.Select(i => new KeyValuePair<string, string>(i.Split('=')[0],i.Split('=')[1]))
.ToDictionary(k => k.Key, k => k.Value);
myDictionary.ToList().ForEach(x => Console.WriteLine($"KEY: {x.Key} VALUE: {x.Value}"));
}
}
see: https://dotnetfiddle.net/Uhekuv
Output:
KEY: Item1 VALUE: value1
KEY: Item2 VALUE: value2
KEY: Item3 VALUE: value3
KEY: Item4 VALUE: value4
CodePudding user response:
You can remove corner brackets and split the string by some delimieter (looks like in your case it will be '='). Then you can use each even index element of returned array as a key and odd as a value and add it to the dictionary. Also you should remove questes before adding dictionary value.
