Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ToDictionary lambda select index and element?

Tags:

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.

like image 261
mowwwalker Avatar asked Mar 23 '12 23:03

mowwwalker


1 Answers

Use the .Select operator first:

strn     .Select((x, i) => new { Item = x, Index = i })     .ToDictionary(x => x.Item, x => x.Index); 
like image 110
Kirk Woll Avatar answered Nov 07 '22 10:11

Kirk Woll