C#表达式按键字段对通用查询进行排序 [英] C# Expression to sort generic query by key field

查看:130
本文介绍了C#表达式按键字段对通用查询进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用方法,我想按其关键字段对IQueryable<T>进行排序(可以放心地假设只有一个).因此:

I have a generic method in which I want to sort an IQueryable<T> by its key field (it is safe to assume there is only one). Thus:

void DoStuff<T>(...) 
{
   IQueryable<T> queryable = ... // given
   PropertyInfo keyField = ... // given
   var sortedQueryable = queryable.OrderBy(<some expression here>);
   ...
}

我如何定义一个Expression来返回TkeyField属性,以便它可以正常工作?

How do I define an Expression that will return the keyField property of T so that this will work?

推荐答案

这不太困难,但是您需要通过反射调用OrderBy,因为您不提前知道键字段的类型.因此,鉴于已经显示的代码,您将执行以下操作:

This isn't too difficult, but you need to invoke the OrderBy with reflection as you don't know the type of the key field ahead of time. So given the code you already show, you would do something like this:

// Build up the property expression to pass into the OrderBy method
var parameterExp = Expression.Parameter(typeof(T), "x");
var propertyExp = Expression.Property(parameterExp, keyField);
var orderByExp = Expression.Lambda(propertyExp, parameterExp);

// Note here you can output "orderByExp.ToString()" which will give you this:
//  x => x.NameOfProperty

// Now call the OrderBy via reflection, you can decide here if you want 
// "OrderBy" or "OrderByDescending"
var orderByMethodGeneric = typeof(Queryable)
    .GetMethods()
    .Single(mi => mi.Name == "OrderBy" && mi.GetParameters().Length == 2);

var orderByMethod = orderByMethodGeneric.MakeGenericMethod(typeof(T), propertyExp.Type);

// Get the result
var sortedQueryable = (IQueryable<T>)orderByMethod
    .Invoke(null, new object[] { queryable, orderByExp });

这篇关于C#表达式按键字段对通用查询进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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