7

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);
2
  • You are saying lambda expressions don't support dynamics? Commented Dec 6, 2011 at 17:40
  • In LinqPad it executes and works well. Commented Dec 6, 2011 at 17:40

2 Answers 2

6

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Indeed the code is in another assembly. The code I posted was an example. Knowing that it won't work across assemblies, I was able to modify the code that creates the list of dynamic objects to sort by the date and then pass the sorted list to the consuming assembly. Thanks for the info!
@Halcyon Cool. The problem is that anon types are internal. There are some hacks that wrap them in a dynamic which allows them to work across assemblies, but indeed it's better to rearchitect the solution.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.