难以实现通用的OrderBy解决方案 [英] Trouble implementing generic OrderBy solution

查看:69
本文介绍了难以实现通用的OrderBy解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个采用IQueryable<T>的方法,并且我想在其中通用实现OrderBy.理想情况下,通过将c => c.SomeProperty作为参数传入,但是我不知道如何使泛型起作用,因此我尝试了使用字符串.但是我得到了错误:

I have a method that takes IQueryable<T> and I want to implement OrderBy generically inside it. Ideally by passing in c => c.SomeProperty in as a parameter but I can't figure out how to get the generics working on that so I've tried it with a string. However I am getting the error:

Incorrect number of parameters supplied for lambda declaration

这是我尝试过的(使用字符串方法)

This is what I tried (using the string method)

var sortSelectorParameter = Expression.Parameter(typeof(T), "c");
var sortSelector = Expression.PropertyOrField(sortSelectorParameter, "ClientId"); // ClientId is the property string

collection = collection.OrderByDescending(Expression.Lambda<Func<T, bool>>(sortSelector));

我很困惑,因为OrderBy只接受一个参数-有什么建议吗?

I am very confused as OrderBy only takes one parameter - any advice?

推荐答案

您需要将参数传递给Expression::Lambda<T>,因为错误提示:

You need to pass the parameter to Expression::Lambda<T>, as the error says:

var sortSelectorParameter = Expression.Parameter(typeof(T), "c");
var sortSelector = Expression.PropertyOrField(sortSelectorParameter, "ClientId"); // ClientId is the property string

collection = collection.OrderByDescending(Expression.Lambda<Func<T, bool>>(sortSelector, sortSelectorParameter ));

您的lambda的"body"引用参数c,该参数由ExpressionParameter实例sortSelectorParameter表示.您需要将此参数实例传递给lambda,以便它知道主体所引用的参数实际上是您要创建的lambda的参数内.

Your "body" for the lambda refers to a parameter c, which is represented by the ExpressionParameter instance sortSelectorParameter. You need to pass this parameter instance to the lambda, so that it knows that the parameter referred to by the body is in fact the in-parameter of the lambda you wish to create.

上面的内容可能会回答您的技术问题,但目前尚不清楚您要达到的目的.如果您只想按编译时知道的顺序进行排序,则不需要任何这些.包装OrderByDescending-方法有什么意义?

The above may answer your technical question, but it is unclear what you are trying to achieve here. If you just want to order by something which you know at compile-time, then you don't need any of this. What is the point of wrapping the OrderByDescending-method?

IQueryable<TElement> MySpecialOrderBy<TElement, TKey>(IQueryable<TElement> source, Expression<Func<TElement, TKey>> keySelector)
{
    return source.OrderByDescending(keySelector);
}

这篇关于难以实现通用的OrderBy解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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