我确信有更好的方法可以做到这一点,但我不知道如何做到这一点。我能用他们所谓的反思吗?
我想按resultList
中的值排序id
,其中id与要排序的属性名称具有相同的值。
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);
}
答案 0 :(得分:3)
这肯定会对您有所帮助:Dynamic LINQ OrderBy using String Names!
类
public class Person
{
public DateTime DateOfBirth { get; set; }
....
}
使用
// 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();
答案 1 :(得分:0)
您可以使用Dynamic LINQ。