mow*_*ker 18 c# lambda delegates anonymous-function todictionary
我有一个字符串string strn = "abcdefghjiklmnopqrstuvwxyz",想要一个字典,如:
Dictionary<char,int>(){
{'a',0},
{'b',1},
{'c',2},
...
}
Run Code Online (Sandbox Code Playgroud)
我一直在尝试这样的事情
strn.ToDictionary((x,i) => x,(x,i)=>i);
Run Code Online (Sandbox Code Playgroud)
...但是我一直在得到关于代表的各种错误,没有采用两个参数,以及未指明的参数等.
我究竟做错了什么?
我更喜欢对答案的提示,所以我对下次需要做的事情有精神上的痕迹,但根据Stackoverflow的性质,答案也很好.
Kir*_*oll 29
.Select首先使用运营商:
strn
.Select((x, i) => new { Item = x, Index = i })
.ToDictionary(x => x.Item, x => x.Index);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
你假设有是这样的过载.看看Enumerable.ToDictionary- 没有提供索引的重载.您可以通过以下方式打电话来伪造它Select:
var dictionary = text.Select((value, index) => new { value, index })
.ToDictionary(pair => pair.value,
pair => pair.index);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10668 次 |
| 最近记录: |