问题通用的LINQ排序依据功能 [英] Problem with Generic Linq OrderBy function

查看:127
本文介绍了问题通用的LINQ排序依据功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一个帖子,使人们使用通用的表情订购数据如下功能:

 公共静态IOrderedQueryable< T>排序依据< T,TKEY的>(
本的IQueryable< T>源表达式来; Func键< T,TKEY的>> FUNC,布尔isDescending){
返回isDescending? source.OrderByDescending(FUNC):source.OrderBy(FUNC);
}

当我尝试使用这个功能,我得到一个错误说的类型或命名空间名称TKEY的'找不到(是否缺少using指令或程序集引用?)我在这里做了愚蠢的事情,但我无法弄清楚。



编辑:



做一点更多的研究后,我认为我的问题是建立在传入它表达的是有可能建立一个。表达式可以包含不同类型的?比方说,我的数据集有一个字符串,一个int和一个布尔值,我想使用上面的泛型函数由任何项目进行排序。我该怎么办呢?



我现在这个工作:

 如果(IsString)
{
表达式来; Func键< T,串>> expString = ...;
//调用排序依据与expString
}
,否则如果(IsInt)
{
表达的影响< Func键< T,INT>> expInt;
//调用排序依据W / expInt
}

我想是这样的:

 表达式来; Func键< T,{东西通用}>!> EXP; 
如果(IsString)
EXP = ...;
,否则如果(IsInt)
EXP = ...;

//调用排序依据与EXP


解决方案

我在这个目标是消除大量的重复代码。除了处理上升/下降我的排序依据功能处理其他一些常用的逻辑具有良好的。假设在原发布函数定义,可以简单地做到这一点:

 如果({需要通过整数排序})
查询=排序依据(objectT,A => a.myIntegerField,ASC);
,否则如果({需要通过字符串排序})
=查询的OrderBy(objectT,A => a.myStringField,ASC);


I saw the following function in a posting which allows one to order data using a generic expression:

public static IOrderedQueryable<T> OrderBy<T, TKey>(
  this IQueryable<T> source, Expression<Func<T, TKey>> func, bool isDescending) {
  return isDescending ? source.OrderByDescending(func) : source.OrderBy(func);
}

When I try to use this function I get an error saying "The type or namespace name "TKey' could not be found (are you missing a using directive or an assembly reference?)". I'm doing something dumb here but I can't figure it out.

Edit:

After doing a bit more research, I think my problem is in building the Expression that I pass into it. Is it possible to build an expression that can contain different types? Let's say my dataset has a string, an int, and a bool and I want to use the generic function above to sort by any of the items. How do I do this?

I have this working now:

if (IsString)
{
   Expression<Func<T, string>> expString = ...;
   // call orderBy with expString
}
else if (IsInt)
{
   Expression<Func<T, int>> expInt;
   // call orderBy w/ expInt
}
:

I want something like:

Expression<Func<T, {something generic!}>> exp;
if (IsString)
    exp = ...;
else if (IsInt)
    exp = ...;
:
// call orderBy with exp

解决方案

My goal in this was to eliminate a lot of repetitious code. In addition to handling the ascending/descending my "OrderBy" function handles some other common logic has well. Assuming the function definition in the original posting, one can simply do this:

if ( {need to sort by integer})
    query = OrderBy(objectT, a => a.myIntegerField, asc);
else if ( {need to sort by string})
    query = OrderBy(objectT, a=> a.myStringField, asc);
:

这篇关于问题通用的LINQ排序依据功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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