C # hash table sorted by keys

I have a hash table with keys in alphabetical order and values ​​in numerical. how to sort a hash table based on keys?

ExchangeA, 200 ExchangeV, 100 ExchangeC, 200 

to be like that

 ExchangeA, 200 ExchangeC, 200 ExchangeV, 100 
+4
source share
6 answers

You can use SortedDictionary for this, which will do key sorting for you. In your case, SortedDictionary<string, int> will work:

 SortedDictionary<string, int> dict = new SortedDictionary<string, int>(); dict.Add("Exchange C", 200); dict.Add("Exchange A", 200); dict.Add("Exchange V", 100); foreach (var kvp in dict) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } 

Output:

 Key = Exchange A, Value = 200 Key = Exchange C, Value = 200 Key = Exchange V, Value = 100 
+10
source

The easiest way I found the "sort" hash table:

 var hash = new Hashtable(); var orderedKeys = hash.Keys.Cast<string>().OrderBy(c => c); // supposing you're using string keys var allKvp = from x in orderedKeys select new{ key = x, value = hash[x] }; 

However, Im does not order the original hash table by only reading its values ​​in an ordered manner.

As in other answers, if you need to save your data, it will be sorted, it is best to use SortedDictionary

+4
source

Due to the nature of the hash tables, you cannot sort them by keyword: they organize their keys in codes based on their hash code, a value outside the hash table. However, you can read key-value pairs in any order you like. Here's how you can do it using LINQ:

 IDictionary<string, int> d = ...; // your hash table var ordered = d.OrderBy(p => p.Key).ToList(); foreach (var p in ordered) { Console.WriteLine("Key: {0} Value: {1}", p.Key, p.Value); } 
+2
source

Use a list instead of a hash (or convert your hash to a dictionary) and do the following:

 var dictionary = new Dictionary<string, int>(); var l = dictionary.Keys.ToList(); l.Sort(); foreach (var key in l) { Console.WriteLine(dictionary[key]); } 
0
source

Using Linq is easy ( using System.Linq ):

 var sortedList = (from kv in MyDictionary select kv order by kv.Key).ToList<KeyValuePair<string, int>>(); 

This returns a list of KeyValuePair<string, int> .

0
source

I used a list to store Hashtable keys and sorted it, and then laid out a Hashtable using this sorted list. Here is my code:

  List<string> lst = new List<string>(); foreach (var key2 in ht.Keys) { lst.Add(key2.ToString()); } lst.Sort(); foreach (var item in lst) { Console.WriteLine(string.Format("{0},{1}", item, ht[item.ToString()])); } 
0
source

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


All Articles