无法与LINQ中OrderBy属性名称进行排序 [英] Unable to sort with property name in LINQ OrderBy
本文介绍了无法与LINQ中OrderBy属性名称进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
错误是
的 LINQ到实体无法识别方法'System.Object的
的GetValue(系统。对象,System.Object的[])'方法,和该方法
不能被翻译成商店表达的
我的代码是
public static GridResult GetAllUsers(int count, int tblsize,string sortcreteria)
{
using (UserEntities entity = new UserEntities())
{
var data = entity.User_Details.Take(count)
.OrderBy(i =>.GetType().GetProperty(sortcreteria).GetValue(i,null))
.Skip(tblsize).ToList();
result.DataSource = data;
result.Count = entity.User_Details.Count();
}
return result;
}
如何使用属性名作为字符串进行排序?
How to sort with property name as string?
推荐答案
就以下扩展名添加到您的代码,你是好去:
Just add the following extension to your code and you're good to go:
using System.Linq;
using System.Linq.Expressions;
using System;
namespace SomeNameSpace
{
public static class SomeExtensionClass
{
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
}
}
}
用法:
.OrderByField(sortcriteria, true)
编辑:
有关支持为 ThenBy
方法,但是下面的方法返回一个 IOrderedQueryable
应采取一切护理:
For support for the ThenBy
method however the following methods returning an IOrderedQueryable
should take care of it all:
public static class SomeExtensionClass
{
private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
{
var param = Expression.Parameter(typeof(T), "p");
var property = Expression.PropertyOrField(param, propertyName);
var sort = Expression.Lambda(property, param);
var call = Expression.Call(
typeof(Queryable),
(!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty),
new[] { typeof(T), property.Type },
source.Expression,
Expression.Quote(sort));
return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
}
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
{
return OrderingHelper(source, propertyName, false, false);
}
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName, bool descending)
{
return OrderingHelper(source, propertyName, descending, false);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName)
{
return OrderingHelper(source, propertyName, false, true);
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName, bool descending)
{
return OrderingHelper(source, propertyName, descending, true);
}
}
这篇关于无法与LINQ中OrderBy属性名称进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文