Using .ToDictionary()

后端 未结 7 1976
北荒
北荒 2020-12-25 09:27

I have a method returning a List, let\'s call it GetSomeStrings().

I have an extension method on string class, returning number of characters in the str

7条回答
  •  鱼传尺愫
    2020-12-25 10:17

    To construct your dictionary, you can do this:

    var strings = new[] { "one", "2", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
    var dictionary = strings.GroupBy(x => x.Length.ToString()).ToDictionary(x => x.Key, x => x);
    

    Notice the "ToString()" usage to turn the Length of the string into a string.

    Also, sorting a dictionary doesn't generally make sense. You can sort the items in each key of the dictionary, or you can sort the keys of the dictionary when you want to loop through them.

    var sortedKeys = dictionary.Keys.OrderBy(x => x);
    var sortedValues = dictionary["1"].OrderBy(x => x);
    

提交回复
热议问题