使用字段名称作为字符串调用OrderBy() [英] Call OrderBy() with a field name as a string

查看:126
本文介绍了使用字段名称作为字符串调用OrderBy()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.NET 4.51,EF 6

I am using .NET 4.51, EF 6

我对存储库层进行了多次调用,我需要在单个字段上按升序或降序进行一些基本排序,例如:

I make a number of calls to my repository layer where I need to do some basic ordering on a single field in either ascending or descending order such as:

GetAllList()的结果是List<T>.现在不幸的是,我必须排序的Id字段并不总是称为IdText字段也不总是.它们可以是其他内容,例如MyIdSomeTextField等.

The result of GetAllList() is a List<T>. Now unfortunately the Id field I have to sort by is not always called Id nor is the Text field. They can be other things such as MyId, SomeTextField and so on.

所以我想知道是否有一种方法可以通过为字段名称提供字符串来完成OrderBy()OrderByDescending()子句:

So I was wondering if there was a way I could do the OrderBy() and OrderByDescending() clauses by supplying a string for the field name something like:

_Repository.GetAllList().OrderBy(r => r."SomeTextField")

通过这种方式,我可以将所有这些代码移至通用方法.

In this way I could move all this code to a common method.

任何指针都非常感谢.

推荐答案

感谢所有人. Rob,您的解决方案与我最终得到的解决方案非常接近.

Thanks to all. Rob, your solution was pretty close to what I ended up with.

根据您的见解,我进行了更多搜索,并在这里遇到了Marc Gravel的答案在IEnumerable< T> 上进行动态LINQ订购(第二篇文章).

Based on your insights I did some more searching and came across Marc Gravel's answer here Dynamic LINQ OrderBy on IEnumerable<T> (second post).

它增加了动态效果作为额外奖励.

It added dynamic's as an additional bonus.

这篇关于使用字段名称作为字符串调用OrderBy()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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