LINQ - include the list <string> in the dictionary <string, string>
I just work on kata during lunch, and I got rid of ...
Here are the steps I'm trying to complete:
- Given the input string, split the string into a new string character
- Given the result of the string array of the previous step, skip the first element in the array
- Given the set of rows obtained in the previous step, create a collection consisting of every 2 elements
In this last statement, I mean, given this set of 4 lines:
{ "string1", "string2", "string3", "string4" }
I have to finish this set of pairs (are these "tuples" the correct member?):
{ { "string1","string2" }, { "string3","string4" } }
I started looking at ToDictionary and then moved on to choosing an anonymous type, but I'm not sure how to say "return the next two lines as a pair."
My code is like this at the time of writing:
public void myMethod() { var splitInputString = input.Split('\n'); var dic = splitInputString.Skip(1).Select( /* each two elements */ ); }
Cheers for the help!
James
Well, you can use (untested):
var dic = splitInputStream.Zip(splitInputStream.Skip(1), (key, value) => new { key, value }) .Where((pair, index) => index % 2 == 0) .ToDictionary(pair => pair.key, pair => pair.value);
The Zip
part will end as follows:
{ "string1", "string2" } { "string2", "string3" } { "string3", "string4" }
... and the Where
pair using the index will skip every other record (which will be a "value with the following key").
Of course, if you really know that you have a List<string>
to start with, you can just access the pairs by index, but that's boring ...