c# 扩展LINQ的order by函数支持通过字符串来指定列名并支持多列
标签:nbsp ide length tps derby TE this sdn 代码
本文借鉴了https://blog.csdn.net/lan_liang/article/details/68523451。
将字符串转换为orderby的linq可以极大地减少重复劳动,可是该怎样将多个字段转换为Order()及ThenBy()表达式呢?可以参照以下代码:
public static IOrderedQueryable OrderBy(this IQueryable q, string condition)
{
string[] conditions = condition.Split(‘,‘);
if (conditions.Length==0)
{
return (IOrderedQueryable) q;
}
IOrderedQueryable res = null;
for (int i = 0; i )
{
string[] strings = conditions[i].Split(" ");
var fieldName = strings[0];
var direction = strings[1];
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, fieldName);
var exp = Expression.Lambda(prop, param);
string method;
if (i==0)
{
method = direction.ToLower() == "asc" ? "OrderBy" : "OrderByDescending";
}
else
{
method = direction.ToLower() == "asc" ? "ThenBy" : "ThenByDescending";
}
Type[] types = { q.ElementType, exp.Body.Type };
var mce = i==0? Expression.Call(typeof(Queryable), method, types, q.Expression, exp): Expression.Call(typeof(Queryable), method, types, res.Expression, exp);
if (conditions.Length == 1)
{
return (IOrderedQueryable)q.Provider.CreateQuery(mce);
}
res = i == 0 ? (IOrderedQueryable) q.Provider.CreateQuery(mce) : (IOrderedQueryable)res.Provider.CreateQuery(mce);
}
return res;
}
IQueryable对象调用Orderby方法,传入"Id desc,Age desc"格式的字符串即可实现多列排序。
c# 扩展LINQ的order by函数支持通过字符串来指定列名并支持多列
标签:nbsp ide length tps derby TE this sdn 代码
原文地址:https://www.cnblogs.com/axel10/p/9240602.html
评论