这是我的查询,如何使用字符串作为orderby参数?
string sortColumn="Title";
var items = (from ltem in ctxModel.Items
where ltem.ItemID == vId
orderby //something here
select ltem).Skip(PageSize * PageIndex).Take(PageSize);更新:
我不能简单地对结果集进行分页,因为我首先需要排序,然后才需要OrderBy。
发布于 2010-05-01 04:01:50
其他人建议使用动态链接或其他库。就我个人而言,,我不会为这么小的任务引入库依赖。但你可以选择的另外两条路径是...
请参阅http://blog.cincura.net/229310-sorting-in-iqueryable-using-string-as-column-name/
在这种情况下考虑Deferred Execution是很重要的。您可以安全地生成返回IQueryable对象的查询,然后对该对象运行对象查询排序。当实际访问数据时,您的查询将只运行一次。
上面的博客文章是一个示例,展示了如何使用Expression API来构建可用于OrderBy的表达式树。这听起来真的很复杂。MSDN文章可能是更好的参考。请参阅MSDN上的How to: Use Expression Trees to Build Dynamic Queries。
或
例如:
ItemType items = default(ItemType);
switch(sortColumn)
{
case "Title":
{
items = ctxModel.Items
.Where(i => i.ItemID == vId)
.OrderBy( i => i.Title);
}
break;
}发布于 2013-03-21 00:00:17
我使用这个帮助器:
public static class OrderExt
{
private static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName, SortDirection descending, bool anotherLevel = false)
{
var param = Expression.Parameter(typeof(T), string.Empty);
var property = Expression.PropertyOrField(param, propertyName);
var sort = Expression.Lambda(property, param);
var call = Expression.Call(
typeof (Queryable),
(!anotherLevel ? "OrderBy" : "ThenBy") +
(descending == SortDirection.Descending ? "Descending" : string.Empty),
new[] {typeof (T), property.Type},
source.Expression,
Expression.Quote(sort));
return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
}
}调用helper,例如这样做:
string sort = HttpContext.Current.Request.QueryString["sort"];
var products = _productRepository.OrderBy(sort, SortDirection.Ascending);发布于 2010-05-01 04:57:17
这是另一种选择,EntitySorter。允许像dynamic LINQ那样处理字符串,但将操作包装在一个对象中,就像Query Object pattern一样。它允许按字符串和类型安全构造进行排序。下面是一些示例:
// Ways of defining an entity sorter
// 1. Using strings:
IEntitySorter<Person> sorter = EntitySorter<Person>
.OrderBy("Address.City")
.ThenByDescending("Id");
// 2. Defining a sorter with lambda's
IEntitySorter<Person> sorter = EntitySorter<Person>
.OrderByDescending(p => p.Name)
.ThenBy(p => p.Id)
.ThenByDescending(p => p.Address.City);
// 3. Using a LINQ query
IEntitySorter<Person> sorter =
from person in EntitySorter<Person>.AsQueryable()
orderby person.Name descending, person.Address.City
select person;
// And you can pass a sorter from your presentation layer
// to your business layer, and you business layer may look
// like this:
static Person[] GetAllPersons(IEntitySorter<Person> sorter)
{
using (var db = ContextFactory.CreateContext())
{
IOrderedQueryable<Person> sortedList =
sorter.Sort(db.Persons);
return sortedList.ToArray();
}
}您可以找到代码here。
https://stackoverflow.com/questions/2747114
复制相似问题