Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

how to order a List<Dictionary<String,object>> the object contains only string

the dictionary is structured as below

[name: mario]
[surname: rossi]
[address: xxxxxx]
[age: 40]

i'd like to order the list of these dictionaries by "age" may you help me please?

i've tried with:

myList.Select(x => x.OrderBy(y=>y.Value)) 

it gives me this error: the value isn't a string(ok i aggree with him, it's an object, i've to cast in some way) but more important is that i can't tell to the "orderby" methods that it must order by age

If I understand correctly, the dictionary contains 4 items? Or is it that each item has these 4 properties? – Oded Nov 13, 2012 at 10:08 You can order each dictionary by age, Doesn't make sense to order the list by it though unless each dictionary only contains objects with the same age? – Tony Hopkinson Nov 13, 2012 at 10:11 @Tony you can't order the contents of a dictionary (a dictionary is unordered), and ordering the dictionaries themselves is ordering the list; why can't you order the list? – Marc Gravell Nov 13, 2012 at 10:13 @MarcGravell It would appear that I put in different interpretation on the question. I read it as each object having those four properties, not each dictionary having those four keys. Lets hope my intepretation as wrong for all the boys who've amassed some points off this... – Tony Hopkinson Nov 13, 2012 at 17:14

You want something along the lines of

var sorted = myList.OrderBy(dict => Convert.ToInt32(dict["age"]));

I 've used Convert.ToInt32 defensively because there's a small chance you are using another data type for the age, and casting (unboxing) to the wrong type would throw an exception.

However! It would be much easier if you used a proper type instead of the dictionary; then it would just be:

myList.Sort((x,y) => x.Age.CompareTo(y.Age));
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.