Order a list by a string value with the same name as the property
I'm sure there's a better way to do this but I don't know how. Could I use what they c开发者_StackOverflow中文版all reflection?
I want to order the resultList
by the value in id
where the id has the same value as the name of the property to order by.
var resultList = repository.GetPersons();
// Order the result based on the value in the string id
if (id == "organisation")
resultList = resultList.OrderBy(p => p.organisation);
else if (id == "surname")
resultList = resultList.OrderBy(p => p.surname);
else if (id == "lastname")
resultList = resultList.OrderBy(p => p.lastname);
else if (id == "adress")
resultList = resultList.OrderBy(p => p.adress);
}
This will surely helps you : Dynamic LINQ OrderBy using String Names!
Class
public class Person
{
public DateTime DateOfBirth { get; set; }
....
}
Use
// First we define the parameter that we are going to use
// in our OrderBy clause. This is the same as "(person =>"
// in the example above.
var param = Expression.Parameter(typeof(Person), "person");
// Now we'll make our lambda function that returns the
// "DateOfBirth" property by it's name.
var mySortExpression = Expression.Lambda<Func<Person, object>>
(Expression.Property(param, "DateOfBirth"), param);
// Now I can sort my people list.
Person[] sortedPeople = people.OrderBy(mySortExpression).ToArray();
You could use Dynamic LINQ.
精彩评论