0

I want to sort below dictionary by Key.

Dictionary<string, string> Numbers;

Sample data:

(100,+100)
(24,+24)
(214,+214)
(3,+3)
(1,+1)

Expected Output:

(1,+1)
(3,+3)
(24,+24)
(100,+100)
(214,+214)

If I use SortedDictionary, my output is

(1,+1)(100,+100)(24,+24)(214,+214)(3,+3)

4
  • Could you use a SortedDictionary instead? msdn.microsoft.com/en-us/library/f7fta44c(v=vs.110).aspx Commented Dec 1, 2015 at 0:05
  • If I use SortedDictionary<string, string> . My output is (1,+1)(100,+100)(24,+24)(214,+214)(3,+3) Commented Dec 1, 2015 at 0:11
  • Have you given any thought to LINQ ? Commented Dec 1, 2015 at 0:13
  • Just for completeness, the reason the sorted dictionary didn't work is because you have a string for the key value. The sort order is correct for a string sort. By using @gaemaf answer you are indicating that the key can be an int value. Your best course of action is to change Numbers to Numbers<int, string> and have the key be an integer everywhere. And just to be pedantic, the sort dictionary result with a string key is (1, +1)(100, +100)(214, +214)(24, +24)(3, +3) Commented Dec 1, 2015 at 1:42

2 Answers 2

2

You can use the SortedDictionary but you need to rearrange your input or preserve your type:

Dictionary<string, string> Numbers = new Dictionary<string, string> {
  {"100","+100"},
  {"24","+24"},
  {"214","+214"},
  {"3","+3"},
  {"1","+1"}};

Numbers = Numbers.OrderBy(key => int.Parse(key.Key)).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);

SortedDictionary<int, string> Numbers1 = new SortedDictionary<int, string> {
  {100,"+100"},
  {24,"+24"},
  {214,"+214"},
  {3,"+3"},
  {1,"+1"}};
Sign up to request clarification or add additional context in comments.

Comments

1

The dictionary type is inherently unordered, but you can use a SortedDictionary instead.

A similar question was answered in more detail here: https://stackoverflow.com/a/2705623/2608569

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.