Halcyon
Halcyon

Reputation: 14941

How To Sort A List With Dynamic Objects

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);

Upvotes: 7

Views: 3123

Answers (2)

Michael Stum
Michael Stum

Reputation: 181004

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)

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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

Upvotes: 3

Related Questions