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);
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.
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.
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.
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)
I verified that your query works in .NET 4.0. Are you missing a reference to Microsoft.CSharp
from your assembly?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With