LINQ排序的列表(myObjects中)列表、LINQ、myObjects

2023-09-03 02:06:53 作者:少女邂逅浪漫

我如何订购通过我的对象列表中传递的字符串值?我需要做分页和我的名单上(中)排序对象分页是没有问题的,但我不;知道谁拿到顺序按工作

How do I order by a passed string value on my list of objects? i need to do paging and sorting on my List(Of) objects the paging is no problem but I don;t know who to get the Order By to work.

下面是我目前做的,它的工作太棒了:

Here is what I am currently doing and it's working great:

Return returnReports.Skip(PageSize * (PageNumber-1)).Take(PageSize).ToList()

我如何得到这个工作?

How do I get this to work?

Return returnReports.OrderBy(SortColumn).Skip(skip).Take(PageSize).ToList()

SortColumn是一个传递的字符串值

SortColumn being a passed string value

推荐答案

VB

Module OrderByExtensions
  <System.Runtime.CompilerServices.Extension()> _
  Public Function OrderByPropertyName(Of T)(ByVal e As IEnumerable(Of T), ByVal propertyName As String) As IOrderedEnumerable(Of T)
    Dim itemType = GetType(T)
    Dim prop = itemType.GetProperty(propertyName)
    If prop Is Nothing Then Throw New ArgumentException("Object does not have the specified property")
    Dim propType = prop.PropertyType
    Dim funcType = GetType(Func(Of ,)).MakeGenericType(itemType, propType)
    Dim parameter = Expression.Parameter(itemType, "item")
    Dim exp = Expression.Lambda(funcType, Expression.MakeMemberAccess(parameter, prop), parameter)
    Dim params = New Object() {e, exp.Compile()}
    Return DirectCast(GetType(OrderByExtensions).GetMethod("InvokeOrderBy", Reflection.BindingFlags.Static Or Reflection.BindingFlags.NonPublic).MakeGenericMethod(itemType, propType).Invoke(Nothing, params), IOrderedEnumerable(Of T))
  End Function
  Private Function InvokeOrderBy(Of T, U)(ByVal e As IEnumerable(Of T), ByVal f As Func(Of T, U)) As IOrderedEnumerable(Of T)
    Return Enumerable.OrderBy(e, f)
  End Function
End Module

C#

public static class OrderByExtensions
{
  public static IOrderedEnumerable<T> OrderByPropertyName<T>(this IEnumerable<T> e, string name)
  {
    var itemType = typeof(T);
    var prop = itemType.GetProperty(name);
    if (prop == null) throw new ArgumentException("Object does not have the specified property");
    var propType = prop.PropertyType;
    var funcType = typeof(Func<,>).MakeGenericType(itemType, propType);
    var parameter = Expression.Parameter(itemType, "item");
    var memberAccess = Expression.MakeMemberAccess(parameter, prop);
    var expression = Expression.Lambda(funcType, memberAccess, parameter);
    var x = typeof(OrderByExtensions).GetMethod("InvokeOrderBy", BindingFlags.Static | BindingFlags.NonPublic);
    return (IOrderedEnumerable<T>)x.MakeGenericMethod(itemType, propType).Invoke(null, new object[] { e, expression.Compile() });
  }
  static IOrderedEnumerable<T> InvokeOrderBy<T, U>(IEnumerable<T> e, Func<T, U> f)
  {
    return e.OrderBy(f);
  }
}