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

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

问题描述

使用实体框架 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 的 Dynamic 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.

推荐答案

首先你需要@Slace写的OrderBy扩展方法此处.所有的功劳都归功于 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. List 被转换为 IQueryable,因为 Enumerable 运算符不采用表达式树.
  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天全站免登陆