james lewis
james lewis

Reputation: 2532

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:

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

Upvotes: 6

Views: 544

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503799

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...

Upvotes: 4

Related Questions