gpt4 book ai didi

c# - Linq-to-Entities 动态排序

转载 作者:IT王子 更新时间:2023-10-29 04:47:52 28 4
gpt4 key购买 nike

这是我的查询,如何使用字符串作为 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);

更新:
我不能只对结果集进行排序,因为我首先需要排序,然后才然后进行分页。

最佳答案

我使用这个助手:

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);
}
}

调用助手,例如这样做:

string sort = HttpContext.Current.Request.QueryString["sort"];
var products = _productRepository.OrderBy(sort, SortDirection.Ascending);

关于c# - Linq-to-Entities 动态排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2747114/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com