如何创建运行时排序的表达式树? [英] How do I create an expression tree for run time sorting?

查看:198
本文介绍了如何创建运行时排序的表达式树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用实体框架4,我试图根据成员名称的集合实现动态排序。基本上,用户可以选择要排序的字段和排序顺序。我已经看了表达式树的例子,不能把它放在一起。以下是一些细节:

Using Entity Framework 4, I'm trying to implement dynamic sorting based on a collection of member names. Basically, the user can select fields to sort and the order of the sorting. I've looked at expression tree examples and can't piece this together. Here are some details:

列名称的集合:

public List<string> sortColumns;
sortColumns = new List<string>();

/// Example subset of video fields.  The collection will vary.
sortColumns.Add("Width");
sortColumns.Add("Height");
sortColumns.Add("Duration");
sortColumns.Add("Title");

视频类定义如下:

public class Video
{
    public string Title { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
    public float Duration { get; set; }
    public string Filename { get; set; }
    public DateTime DateCreated { get; set; }
    .
    .
    .
}
public List<Video> Videos;

我想做的是通过sortColumns集合枚举在运行时构建一个表达式树。此外,用户可以指定升序或降序排序,表达式树也应该处理。

What I would like to do is enumerate through the sortColumns collection to build an expression tree at run time. Also, the user could specify either ascending or descending sorting and the expression tree should handle either.

我为VS 2008尝试了动态LINQ库,但不显示在VS 2010中工作(我可能会做错事)。

I tried the Dynamic LINQ library for VS 2008, but it doesn't appear to work in VS 2010. (I could be doing something wrong.)

底线是我需要一个表达式树,以根据用户输入动态地对视频集合进行排序。任何帮助将不胜感激。

The bottom line is I need an expression tree to dynamically sort the Videos collection based on user input. Any help would be appreciated.

推荐答案

首先你需要 OrderBy 方法@Slace写了此处。所有这一切都归功于 Slace ,获得了令人敬畏的代码,是解决方案中最困难的部分!我做了一些修改,以适应您的具体情况:

First you need the OrderBy extension method that @Slace wrote here. All credit to Slace for an awesome piece of code and by far the most difficult part of the solution! I made a slight modification for it to work with your specific situation:

public static class QueryableExtensions
{
    public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortProperty, ListSortDirection sortOrder)
    {
        var type = typeof(T);
        var property = type.GetProperty(sortProperty);
        var parameter = Expression.Parameter(type, "p");
        var propertyAccess = Expression.MakeMemberAccess(parameter, property);
        var orderByExp = Expression.Lambda(propertyAccess, parameter);
        var typeArguments = new Type[] { type, property.PropertyType };
        var methodName = sortOrder == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
        var resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, Expression.Quote(orderByExp));

        return source.Provider.CreateQuery<T>(resultExp);
    }
}

创建一个排序列表的方法。以下方法需要注意几件事:

Create a method to sort the list. A couple of things to note in the method below:


  1. 列表< string> 被转换为 IQueryable< string> ,因为可枚举运算符不会采用表达式树。

  2. 该方法以相反的顺序遍历排序列列表(假设您希望将列表中的第一个项目列为最高排序优先级)

  1. The List<string> is converted to an IQueryable<string> since Enumerable operators don't take expression trees.
  2. The method iterates through the list of sort columns in reverse order (assuming you want to give the first item in the list the highest sort priority)

private void PrintVideoList(IEnumerable<string> sortColumns, ListSortDirection sortOrder)
{
    var videos = this.GetVideos();
    var sortedVideos = videos.AsQueryable();

    foreach (var sortColumn in sortColumns.Reverse())
    {
        sortedVideos = sortedVideos.OrderBy(sortColumn, sortOrder);
    }

    // Test the results
    foreach (var video in sortedVideos)
    {
        Console.WriteLine(video.Title);
    }
}

然后,您应该可以使用这样的方法:

You should then be able to use the method like this:

// These values are entered by the user
var sortColumns = new List<string> { "Width", "Title", "Height" };
var sortOrder = ListSortDirection.Ascending;

// Print the video list base on the user selection
this.PrintVideoList(sortColumns, sortOrder);

这篇关于如何创建运行时排序的表达式树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆