I have a string of data:
Key1=Value1,Key2=Value2,KeyN=ValueN
I'm trying to split the string into
List<KeyValuePair<string, string>>
I can easily do this:
List<string[]> values = item.Split( ',' ).Select( p => p.Split( '=' ) ).ToList();
but I just can't figure out the way to get that into the List of KeyValuePair's. The closest I've gotten so far is:
List<KeyValuePair<string, string>> values = item.Split( ',' )
.Select( p => new KeyValuePair<string, string>(){ p.Split( '=' ) } ).ToList();
But that's still a bit off :(
I know I can easily do it with a loop but I'd really like to get it working in Linq as practice makes perfect. I've seen quite a few examples already of similar questions like this one, but I can't seem to join the dots between those questions and mine so please forgive me if I've accidentally posted a duplicate.
Any help would really be appreciated, thanks :)
What you've done so far is good. Then, you have two ways to achieve what you want:
ToKeyValuePairpublic static KeyValuePair<string, string> ToKeyValuePair(string[] array)
{
if (array.Length != 2)
throw new ArgumentException("The array must contain exactly 2 elements.");
return new KeyValuePair<string, string>(array[0], array[1]);
}
var values = (item.Split( ',' )
.Select( p => ToKeyValuePair(p.Split( '=' ))))
.ToList();
If I convert the above line into query syntax:
var values = (from p in item.Split( ',' )
select ToKeyValuePair(p.Split( '=' )))
.ToList();
Not much has changed.
But, thanks to this new syntax, it is quite easy to remove the usage of ToKeyValuePair(...) thanks to the let clause:
var values = (from p in item.Split( ',' )
let splittedP = p.Split( '=' ) // Declares a variable
select new KeyValuePair<string, string>(splittedP[0], splittedP[1]))
.ToList();
Of course, the last line can be written with Extention methods syntax (ie with .Select(p=>...)), but is hard to read:
var values = (item.Split(',')
.Select(p => new { p, splittedP = p.Split('=') })
.Select(p => new KeyValuePair<string, string>(p.splittedP[0], p.splittedP[1])))
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With