Dynamically Sorting with LINQ

后端 未结 9 2049
自闭症患者
自闭症患者 2020-12-16 04:57

I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name

9条回答
  •  旧时难觅i
    2020-12-16 05:40

    You need to build an Expression Tree and pass it to OrderBy.
    It would look something like this:

    var param = Expression.Parameter(typeof(MyClass));
    var expression = Expression.Lambda>(
        Expression.Property(param, sortProperty),
        param
    );
    

    Alternatively, you can use Dynamic LINQ, which will allow your code to work as-is.

提交回复
热议问题