C# ToDictionary lambda select index and element?

mowwwalker picture mowwwalker · Mar 24, 2012 · Viewed 12.5k times · Source

I have a string like string strn = "abcdefghjiklmnopqrstuvwxyz" and want a dictionary like:

Dictionary<char,int>(){
    {'a',0},
    {'b',1},
    {'c',2},
    ...
}

I've been trying things like

strn.ToDictionary((x,i) => x,(x,i)=>i);

...but I've been getting all sorts of errors about the delegate not taking two arguments, and unspecified arguments, and the like.

What am I doing wrong?

I would prefer hints over the answer so I have a mental trace of what I need to do for next time, but as per the nature of Stackoverflow, an answer is fine as well.

Answer

Kirk Woll picture Kirk Woll · Mar 24, 2012

Use the .Select operator first:

strn
    .Select((x, i) => new { Item = x, Index = i })
    .ToDictionary(x => x.Item, x => x.Index);