本文介绍了C#ToDictionary Lambda选择索引和元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像string strn = "abcdefghjiklmnopqrstuvwxyz"这样的字符串,并且想要一个像这样的字典:

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

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

我一直在尝试

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.

我做错了什么?

与答案相比,我更希望有提示,因此我对下一次需要做的事情有心理上的了解,但是根据Stackoverflow的性质,答案也很好.

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.

推荐答案

首先使用.Select运算符:

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

这篇关于C#ToDictionary Lambda选择索引和元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 15:31