Search code examples
c#linqdynamicsql-order-byexpandoobject

How do you OrderBy in C# and LINQ using a parameter defined in runtime for a List<dynamic> where each dynamic is an ExpandoObject


I have a data that is generated at runtime and stored as a List<dynamic> called "Reports".

"Reports" contains many "Report" which are also generated at run time as a new ExpandoObject().

Each "Report" is assigned various properties (e.g. Report.Name, Report.Value, Report.Order, etc) at runtime before being added to "Reports".

The user is able to select which property they want to view (which are pre-defined).

I want to use LINQ OrderBy to sort "Reports" by the user defined property.


Solution

  • You can cast to IDictionary<string, object> and use square bracket indexers with the property name string, e.g.

    dynamic report1 = new ExpandoObject();
    report1.Name = "Foo";
    dynamic report2 = new ExpandoObject();
    report2.Name = "Bar";
    
    var reports = new[] { report1, report2 }.ToList();    
    
    var sortBy = "Name";
    
    var first = reports.OrderBy(x => ((IDictionary<string, object>)x)[sortBy]).First();
    
    Console.WriteLine(first.Name); // Bar