Search code examples
c#collectionsgeneric-collections

Adding sorted data into a hashtable or Dictionary while reading the data from file


I have a file with contains as
A,15
B,67
C,45
D,10

I am reading the data from file, but i wanted to read the data into a dictionary or hashtable but the data sould be sorted into it by its value that is
B,67
C,45
A,15
D.10

If Any other List will work as efficient manner, please suggest

Thanks


Solution

  • A Dictionary<,>/Hashtable has no defined sort; that will not work. A SortedDictionary<,> is sorted by key, not by value, so that won't work. Personally, I think you should just use a regular List<T> (for some simple T with the two properties), and after loading it:

    list.Sort((x,y) => y.SecondProp.CompareTo(x.SecondProp));
    

    the subtle x/y switch in there achieves "descending". If you also need the data keyed by the first property, then separately store a Dictionary<string,int>.

    Full example:

    class Program
    {
        static void Main()
        {
            List<MyData> list = new List<MyData>();
            // load the data (replace this with a loop over the file)
            list.Add(new MyData { Key = "B", Value = 67 });
            list.Add(new MyData { Key = "C", Value = 45 });
            list.Add(new MyData { Key = "A", Value = 15 });
            list.Add(new MyData { Key = "D", Value = 10 });
            // sort it
            list.Sort((x,y)=> y.Value.CompareTo((x.Value)));
            // show that it is sorted
            foreach(var item in list)
            {
                Console.WriteLine("{0}={1}", item.Key, item.Value);
    
            }
        }
    }
    
    internal class MyData
    {
        public string Key { get; set; }
        public int Value { get; set; }
    }