2

I have this code:

List<KeyValuePair<String,List<MyObject>>> aux = retEmpty.ToList();
aux.ForEach(x => ret.Add(x.Key, x.Value));

I need to sort "ret" by the first element("string"). I tried a couple example but none of them work. Any help?

Ricardo Neves
  • 495
  • 3
  • 11
  • 24

4 Answers4

2

Did you try replacing the second line with:

aux.OrderBy(x=>x.Key).ToList().ForEach(x=>ret.Add(x.Key,x.Value));

?

Boluc Papuccuoglu
  • 2,318
  • 1
  • 14
  • 24
  • This won't work because ret is a simple Dictionary and the [order of elements in a Dictionary is non-deterministic](http://stackoverflow.com/a/4007787/2504607) – Kabbalah Nov 13 '13 at 12:46
  • Yes, I posted the answer before the comments on ret being a Dictionary. – Boluc Papuccuoglu Nov 13 '13 at 12:47
  • 1
    Fair enough. I made my comment just to clarify for future reference. – Kabbalah Nov 13 '13 at 12:50
  • @RicardoNeves Be careful using this method because it's just pure luck that a Dictionary returns values in the same order they where added. – Kabbalah Nov 13 '13 at 12:51
1

Based on your comment you can simply use a SortedDictionary

var ret = new SortedDictionary<String,List<MyObject>>();
ret.Add(...
VladL
  • 12,769
  • 10
  • 63
  • 83
0

Did you try something like:

var v = from obj in ret
    orderby obj.Key
    select obj
Noctis
  • 11,507
  • 3
  • 43
  • 82
0

ret looks like a Dictionary. If this assumption is correct you could use a SortedDictionary instead.

Kabbalah
  • 471
  • 1
  • 5
  • 16