1
public class Person
{
public string name { get; set; }
public Email email { get; set; }
}
public class Email
{
public string desc { get; set; }
}
public static IEnumerable<T> Sort<T>(this IEnumerable<T> source, string sortExpression, bool desc)
{
var param = Expression.Parameter(typeof(T), string.Empty);
try
{
var property = Expression.Property(param, sortExpression);
var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, typeof(object)), param);
if (desc)
{
return source.AsQueryable<T>().OrderByDescending<T, object>(sortLambda);
}
return source.AsQueryable<T>().OrderBy<T, object>(sortLambda);
}
catch (ArgumentException)
{
return source;
}
}
List<Person> vet = new List<Person>();
Person p = new Person { name = "aaa", email = new Email { desc = "[email protected]" } };
Person pp = new Person { name = "bbb", email = new Email { desc = "[email protected]" } };
vet.Add(p);
vet.Add(pp);
vet.Sort("name",true); //works
vet.Sort("email.desc",true) // doesnt work
有人能幫助我嗎?擴展方法排序父對象內的列表