6

I have a list which contains a dictionary of ExpandoObjects. Im binding this to a grid but now I want to sort the list.

        var rows = new List<dynamic>();
        for (int i = 0; i < 1000; i++)
        {
            dynamic expandy = new ExpandoObject();
            var dictionary = (IDictionary<string, object>)expandy;

            dictionary.Add("ID", i);
            dictionary.Add("Name", "Name" + i);
            rows.Add(dictionary);
        }

So looking at the test code above how would I sort rows (ascending or decending) say on "ID" or "Name" or any other property that I dynamically add?

A bit more info, I'm looking to sort it like this (this doesnt work);

            var newOrder = from r in rows
                     orderby ("Name") ascending 
                     select r;
armasanea
  • 434
  • 3
  • 7
WooHoo
  • 1,912
  • 17
  • 22

2 Answers2

5

WooHoo's answer does not work for Dynamic.ExpandoObject; this works:

var newOrder = rows.OrderByDescending(x =>((IDictionary<string,object>)x)["Name"]);
Cleb
  • 25,102
  • 20
  • 116
  • 151
5

Not sure how I missed this but anyway this works,

var newOrder = rows.OrderByDescending(x => x["Name"]);
WooHoo
  • 1,912
  • 17
  • 22