Linq 和排序依据
我有一个通用类,它可以使用通用 OrderBy 参数,
该类如下所示。
class abc<T> where T : myType
{
public abc(....., orderBy_Argument ){ ... }
void someMethod(arg1, arg2, bool afterSort = false)
{
IEnumerable<myType> res ;
if ( afterSort && orderBy_Argument != null )
res = src.Except(tgt).OrderBy( .... );
else
res = src.Except(tgt);
}
}
orderBy 可以是各种类型,
例如
.OrderBy( person => person.FirstName )
.OrderBy( person => person.LastName )
.OrderBy( person => person.LastName, caseInsensitive etc )
目标是使 orderBy 成为一个论点,而不是在
任何想法中烘焙它?
I have a generic class which could use a generic OrderBy argument
the class is as follows
class abc<T> where T : myType
{
public abc(....., orderBy_Argument ){ ... }
void someMethod(arg1, arg2, bool afterSort = false)
{
IEnumerable<myType> res ;
if ( afterSort && orderBy_Argument != null )
res = src.Except(tgt).OrderBy( .... );
else
res = src.Except(tgt);
}
}
The orderBy could be of various types
e.g.
.OrderBy( person => person.FirstName )
.OrderBy( person => person.LastName )
.OrderBy( person => person.LastName, caseInsensitive etc )
The goal is to make the orderBy an argument rather than bake it in
any ideas ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要将参数传递给
OrderBy
,传递转换IEnumerable
(或IQueryable
)的函数,如可能是)。修改您的示例以执行以下操作会产生以下程序:
当然,这是一个非常奇怪的排序和无意义的
someMethod
- 但它表明您可以传入一个非常灵活的排序委托(实际上,委托可以做的不仅仅是排序),只需很短的实现。Don't pass in the arguments to
OrderBy
pass in a function which transforms anIEnumerable
(orIQueryable
, as it may be).Modifying your example to do so results in the following program:
Of course, this is a pretty weird ordering and a nonsensical
someMethod
- but it demonstrates that you can pass in a very flexible sorting delegate (indeed, the delegate could do more than just sort) with only a very short implementation.只需将排序键作为委托传递即可:
缺点是它需要额外的类型参数......
Just pass the sort key as a delegate:
The drawback is that it requires an extra type parameter...