使用.ToDictionary() [英] Using .ToDictionary()
问题描述
我返回一个列表的方法,我们称之为 GetSomeStrings()
。
I have a method returning a List, let's call it GetSomeStrings()
.
我有一个扩展方法对串类,在字符串中返回的字符数,例如。 myString.Number('A')
。
I have an extension method on string class, returning number of characters in the string, eg. myString.Number('A')
.
我想,在一个单一的线,抢字典。该词典的条目中包含的字符串,字符串中选定的字符数
I would like to, in a single line, grab a dictionary. An entry of the dictionary contains the string, and the number of a chosen character in the string.
其实我做到以下几点:
var myDic = GetSomeStrings().ToDictionary(x=>x.Number('A'));
这给了我一本词典< INT,串>
;我想关键的字符串。
which gives me a dictionary <int,string>
; I would like the key as the string.
之后,我想订的int值的字典。这可能包括在这之前的声明?
After, I'd like to order the dictionary on the int value. It is possible to include this in the previous statement ?
我真的想避免集合枚举排序或创建列表,字典这就是我实际上离不开烦恼。谢谢您的优化帮助!
I'd really like to avoid a collection enumeration to sort or create the dictionary from the list, which is what i do actually without troubles. Thank you for your optimization help !
推荐答案
的< A HREF =https://msdn.microsoft.com/de-de/library/system.linq.enumerable.todictionary%28v=vs.110%29.aspx> ToDictionary()
方法过载,它有两个lamdba表达式 <子>(鸡蛋里挑骨头:代表);一个键和一个值结果
,例如:
Edit
The ToDictionary()
method has an overload that takes two lamdba expressions (nitpick: delegates); one for the key and one for the value.
For example:
var myDic = GetSomeStrings().ToDictionary(x => x, x => x.Number('A'));
请注意,通过返回的值GetSomeStrings()
必须是唯一的。
Note that the values returned by GetSomeStrings()
must be unique.
NET的的 词典< TKEY的,TValue>
是无序的;它完全不能进行排序
.Net's Dictionary<TKey, TValue>
is unordered; it cannot be sorted at all.
相反,你可以排序的字典,当你使用它,就像这样:
Instead, you can sort the dictionary when you use it, like this:
foreach(KeyValuePair<string, int> kvp in dict.OrderBy(kvp => kvp.Value))
这篇关于使用.ToDictionary()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!