Key-based dictionary sorting

I need to order a dictionary in VB.net based on keys. Keys and values ​​are all strings. The dictionary does not have .Sort() . Is there a way to do this without having to write my own sorting algorithm?

+6
source share
3 answers

SortedDictionary comes to mind, but is sorted by key only.

Otherwise, this answer may help. How do you sort the C # dictionary by value? .

+15
source

If you need to save the main dictionary and not use SortedDictionary, you can use LINQ to return IEnumerable based on what you need:

 Dim sorted = From item In items Order By item.Key Select item.Value 

Sorting a Dictionary is likely to give more performance when reused, however, until you need to invert this view at some point in the future.

+2
source

It is in vb.net that execute this code:

  Dim myDict As New Dictionary(Of String, String) myDict.Add("one", 1) myDict.Add("four", 4) myDict.Add("two", 2) myDict.Add("three", 3) Dim sortedDict = (From entry In myDict Order By entry.Value Ascending).ToDictionary(Function(pair) pair.Key, Function(pair) pair.Value) For Each entry As KeyValuePair(Of String, String) In sortedDict Console.WriteLine(String.Format("{0,10} {1,10}", entry.Key, entry.Value)) Next 
+1
source

Source: https://habr.com/ru/post/899632/


All Articles