C# Sort List by its property which is string of datetime

Based on your comments on the answers you are looking for a reflection based solution.

The reflection part, to get the value of a property based on the name:

x.GetType().GetProperty(propertyName).GetValue(x, null)

Try this:

var propetyName = "StringAsDate";
var listSorted = list.OrderByDescending(x => DateTime.Parse(Convert.ToString(x.GetType().GetProperty(propertyName).GetValue(x, null))));

If the Property is already of type DateTime a cast would be sufficient

var propetyName = "StringAsDate";
var listSorted = list.OrderByDescending(x => (DateTime)x.GetType().GetProperty(propertyName).GetValue(x, null));

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top