Sorting in Dictionary C#

.net, asp.net, c#, vb.net

Solution

The `Dictionary<TKey, TValue>` type is an unordered collection in .Net. If you want ordering then you need to use `SortedDictionary<TKey, TValue>` instead and provide a custom `IComparer<string>` which counts the `/` values in the string.

sealed class SlashComparer : IComparer<string> { 
  static int CountSlashes(string str) { 
    if (String.IsNullOrEmpty(str)) { 
      return 0;
    }

    int count = 0;
    for (int i = 0; i < str.Length; i++) {
      if (str[i] == '/') {
         count++;
      }
    }
    return count;
  }

  public int Compare(string left, string right) { 
    int leftCount = CountSlashes(left);
    int rightCount = CountSlashes(right);
    return rightCount - leftCount;
  }
}

To use with a `SortedDictionary` the only thing you need to change is the declaration

var comparer = new SlashComparer();
var rList = new SortedDictionary<string, string>(comparer);

The rest of the code can remain the same

Problem

I Have one Dictionary ``` Dictionary<string, string> rList = new Dictionary<string, string>(); rList .Add("/a/b/c", "35"); rList .Add("/a/c/f/v", "25"); rList .Add("/a/r/d/c/r/v", "29"); rList .Add("/a", "21"); rList .Add("/a/f, "84"); ``` I just want to sort this Dictionary based on the number of number of '/' present in the key. my expected out put is , ``` ("/a/r/d/c/r/v", "29") ("/a/c/f/v", "25") ("/a/b/c", "35") ("/a/f, "84") ("/a", "21") ```

Original source