C# ToDictionary lambda select index and element?

落爺英雄遲暮 提交于 2019-11-30 14:37:33

问题


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.


回答1:


Use the .Select operator first:

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



回答2:


What am I doing wrong?

You're assuming there is such an overload. Look at Enumerable.ToDictionary - there's no overload which provides the index. You can fake it though via a call to Select:

var dictionary = text.Select((value, index) => new { value, index })
                     .ToDictionary(pair => pair.value,
                                   pair => pair.index);



回答3:


You could try something like this:

    string strn = "abcdefghjiklmnopqrstuvwxyz";

Dictionary<char,int> lookup = strn.ToCharArray()
    .Select( ( c, i ) => new KeyValuePair<char,int>( c, i ) )
        .ToDictionary( e => e.Key, e => e.Value );


来源:https://stackoverflow.com/questions/9847547/c-sharp-todictionary-lambda-select-index-and-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!