按与属性同名的字符串值排序列表
本文关键字:字符串 排序 列表 属性 | 更新日期: 2023-09-27 18:10:10
我相信有更好的方法来做到这一点,但我不知道怎么做。我可以用所谓的反射吗?
我想按id
中的值排序resultList
,其中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);
}
这肯定会对您有所帮助:使用字符串名称动态LINQ顺序!
类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();
你可以使用Dynamic LINQ