How to sort a List<dynamic> containing ExpandoObjects
Asked Answered
E

2

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;
Eisteddfod answered 23/3, 2012 at 14:48 Comment(4)
Why make it dynamic if your always putting a Dictionary in it?Hummingbird
Assuming I change it to var rows = new List<IDictionary<string, object>> how would i sort it?Eisteddfod
How do you want it sort? Which value in the Dictionary do you want to use?Hummingbird
Sort it ascending or decending. On any property in the dictionary.Eisteddfod
E
5

Not sure how I missed this but anyway this works,

var newOrder = rows.OrderByDescending(x => x["Name"]);
Eisteddfod answered 23/3, 2012 at 15:51 Comment(0)
W
5

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

var newOrder = rows.OrderByDescending(x =>((IDictionary<string,object>)x)["Name"]);
Windham answered 7/7, 2015 at 8:2 Comment(4)
What do you mean by "This does not work for Dynamic.ExpandoObject"? What is "this"; your own answer or do you refer to another answer?Disheveled
I was referring to the code var newOrder = rows.OrderByDescending(x => x["Name"]); when used in Dynamic.ExpandoObject.Windham
You mean WooHoo's answer from above?Disheveled
Yes, I tried it and it wasn't working, for Dynamic.ExpandoObject but for ExpandoObject alone its working.Windham

© 2022 - 2024 — McMap. All rights reserved.