当前位置:  开发笔记 > 编程语言 > 正文

linq命令列表(MyObjects)

如何解决《linq命令列表(MyObjects)》经验,为你挑选了1个好方法。

如何通过我的对象列表中的传递字符串值进行排序?我需要在我的List(Of)对象上进行分页和排序,分页没有问题,但我不知道是谁让Order By工作.

这是我目前正在做的事情,它的工作很棒:

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

我如何让它工作?

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

SortColumn是传递的字符串值



1> Mehrdad Afsh..:

VB

Module OrderByExtensions
   _
  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 OrderByPropertyName(this IEnumerable 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)x.MakeGenericMethod(itemType, propType).Invoke(null, new object[] { e, expression.Compile() });
  }
  static IOrderedEnumerable InvokeOrderBy(IEnumerable e, Func f)
  {
    return e.OrderBy(f);
  }
}

推荐阅读
和谐啄木鸟
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有