Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - turn List<string> into Dictionary<string,string>

I'm just working on a Kata on my lunch and I've come unstuck...

Here's the steps I'm trying to follow:

  • Given an input string, split the string by the new line character
  • Given the string array result of the previous step, skip the first element in the array
  • Given the collection of strings resulting from the previous step, create a collection consisting of every 2 elements

In that last statement what I mean is, given this collection of 4 strings:

{
    "string1",
    "string2",
    "string3",
    "string4"
}

I should end up with this collection of pairs (is 'tuples' the right term?):

{
    { "string1","string2" },
    { "string3","string4" }
}

I started looking at ToDictionary, then moved over to selecting an anonymous type but I'm not sure how to say "return the next two strings as a pair".

My code looks similar to 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

like image 737
james lewis Avatar asked Jul 06 '12 12:07

james lewis


1 Answers

Well, you could 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 up with:

{ "string1", "string2" }
{ "string2", "string3" }
{ "string3", "string4" }

... and the Where pair using the index will skip every other entry (which would be "value with the next key").

Of course if you really know you've got a List<string> to start with, you could just access the pairs by index, but that's boring...

like image 75
Jon Skeet Avatar answered Nov 09 '22 08:11

Jon Skeet