按字符串值排序列表,其名称与属性相同

时间:2011-09-30 07:11:25

标签: c# linq

我确信有更好的方法可以做到这一点,但我不知道如何做到这一点。我能用他们所谓的反思吗?

我想按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);
}

2 个答案:

答案 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