Click here to Skip to main content
15,896,912 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to sort dictionary values collection like values are 4 5/8
6  3/4
9  3/4
11 1/4
15 1/4
8  1/2
11 7/8
14 3/4
16
19 5/8
13 1/2
7
15
23 3/4
7  3/4
11 3/8
12 1/2
7  1/8
16 1/16
12
9
5  1/2

Thanks in advance .
Posted
Updated 1-Jan-14 0:17am
v3
Comments
Karthik_Mahalingam 1-Jan-14 5:57am    
this is not a dictionary collection...

Those aren't Dictionary entries: a Dictionary is a specific collection that has a Key (which must be unique) and a Value (which doesn't have to be).

Dictionaries are not normally sorted: it works as a Hash Table, so sorting by key or value would slow down access. There is however a SortedDictionary class that does sort by Key, but retrieval is slower than a standard Dictionary as it is stored as a list, rather than a Hash Table.

If, however, you have a list containing string values of fractions, and you want to sort that, you need to convert them to a numeric value first:
C#
private void myButton_Click(object sender, EventArgs e)
    {
    List<string> fractions = new List<string>() {
            "6 3/4", "9 3/4", "11 1/4", "15 1/4", "8 1/2",
            "11 7/8","14 3/4","16","19 5/8","13 1/2","7"};
    List<string> sortedFractions = fractions.OrderBy(f => ToValue(f)).ToList();
    foreach (string s in sortedFractions)
        {
        Console.WriteLine(s);
        }
    }
private static double ToValue(string fraction)
    {
    double result = 0.0;
    string[] parts = fraction.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
    if (parts.Length > 0)
        {
        result = double.Parse(parts[0]);
        if (parts.Length > 1)
            {
            parts = parts[1].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length == 2)
            result += double.Parse(parts[0]) / double.Parse(parts[1]);
            }
        }
    return result;
    }
 
Share this answer
 
Comments
raneshtiwari 1-Jan-14 9:05am    
Thank you @OriginalGriff
OriginalGriff 1-Jan-14 9:15am    
You're welcome!
Hi,

Please see the below link. It might be helpful to you..

http://www.dotnetperls.com/sort-dictionary[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900