Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Sort A List With Dynamic Objects

Tags:

c#

linq

I have a list that holds objects of type dynamic. When I use the LINQ OrderBy method, I get an error saying 'object' does not contain a definition for 'Date'. What can I do to sort my list by the date?

List<dynamic> employees = new List<dynamic>();

employees.Add(new
{
    ID = 1,
    Name = "Larry",
    Date = new DateTime(2010, 10, 1),
});

employees.Add(new
{
    ID = 2,
    Name = "Clint",
    Date = new DateTime(2011, 5, 28),
});

employees.Add(new
{
    ID = 3,
    Name = "Jason",
    Date = new DateTime(2011, 7, 6),
});

var query = employees.OrderBy(x => x.Date);
like image 557
Halcyon Avatar asked Dec 06 '11 17:12

Halcyon


People also ask

How to sort dynamic List in c#?

function void sortDynamicData(typeOfClass,SortKey) { List<dynamic> results = null; //results might be of any type it may contain students data or books data or professors data, hence I took as dynamic results = services.

How to handle dynamic objects in c#?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.

Can you sort a list in C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.


2 Answers

Is the code that you've shown in the same Assembly?

Anonymous Types won't work across assemblies, and the "Object doesn't contain this definition" error is a typical sign of using an anonymous type from two different assemblies

(e.g., in an ASP.net MVC page the Controller may return an anonymous type as a model and the View may try to use it => blows up with exactly that error)

like image 70
Michael Stum Avatar answered Oct 20 '22 11:10

Michael Stum


I verified that your query works in .NET 4.0. Are you missing a reference to Microsoft.CSharp from your assembly?

like image 3
Sergey Kalinichenko Avatar answered Oct 20 '22 11:10

Sergey Kalinichenko