How to simplify LINQ Dynamic Order BY?

Func<article, object> orderByFunc = null;
 switch (OrderBy)
{
 case "AuthorID":
 orderByFunc = ob => ob.AuthorID;
break;
 case "Created":
 orderByFunc = ob => ob.Created;
break;
 case "Title":
 orderByFunc = ob => ob.Title;
break;
default:
 case "ID":
 orderByFunc = ob => ob.ID;
break;
}

 List</article>
ArticlesList = new List
(); switch (OrderWay) { default: case "DESC": ArticlesList = getDB().Article.OrderByDescending(orderByFunc).Skip(Page * Limit).Take(Limit).ToList(); break; case "ASC": ArticlesList = getDB().Article.OrderBy(orderByFunc).Skip(Page * Limit).Take(Limit).ToList(); break; }

There is such a code, whether it is possible to reduce the switch-and in a few lines?(Not to write every time "orderByFunc = ob => ob.FieldName", and write once orderByFunc = какаяТоНеведомаяФункцияДляПолученияполяизлюбогокласса(OrderBy)) the Variable "OrderBy" always corresponds to the name field to be sorted.
June 14th 19 at 20:47
1 answer
June 14th 19 at 20:49
Solution
Func<article, object> orderByFunc = (a) => 
 typeof(Article).GetProperty(OrderBy).GetValue(a);</article>
Thanks already tried this design but a little true it was recorded) and your work. Found the solution, I think to remake, given the ASC and DESC sort that would be from the last switch to get rid of)

public static class QueryableHelper
{
 public static IQueryable<tmodel> OrderBy<tmodel>(this IQueryable<tmodel> q, string name)
{
 Type entityType = typeof(TModel);
 PropertyInfo p = entityType.GetProperty(name);
 MethodInfo m = typeof(QueryableHelper).GetMethod("OrderByProperty").MakeGenericMethod(entityType, p.PropertyType);
 return (IQueryable<tmodel>)m.Invoke(null, new object[] { q, p });
}

 public static IQueryable<tmodel> OrderByDescending<tmodel>(this IQueryable<tmodel> q, string name)
{
 Type entityType = typeof(TModel);
 PropertyInfo p = entityType.GetProperty(name);
 MethodInfo m = typeof(QueryableHelper).GetMethod("OrderByPropertyDescending").MakeGenericMethod(entityType, p.PropertyType);
 return (IQueryable<tmodel>)m.Invoke(null, new object[] { q, p });
}

 public static IQueryable<tmodel> OrderByPropertyDescending<tmodel, tret>(IQueryable<tmodel> q, PropertyInfo p)
{
 ParameterExpression pe = Expression.Parameter(typeof(TModel));
 //Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object));
 Expression se = Expression.Convert(Expression.Property(pe, p), typeof(TRet));
 return q.OrderByDescending(Expression.Lambda<func<tmodel, tret>>(se, pe));
}

 public static IQueryable<tmodel> OrderByProperty<tmodel, tret>(IQueryable<tmodel> q, PropertyInfo p)
{
 ParameterExpression pe = Expression.Parameter(typeof(TModel));
 //Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object));
 Expression se = Expression.Convert(Expression.Property(pe, p), typeof(TRet));
 return q.OrderBy(Expression.Lambda<func<tmodel, tret>>(se, pe));
}
 }</func<tmodel,></tmodel></tmodel,></tmodel></func<tmodel,></tmodel></tmodel,></tmodel></tmodel></tmodel></tmodel></tmodel></tmodel></tmodel></tmodel></tmodel>
- marietta.Ullrich3 commented on June 14th 19 at 20:52
found somewhere this method, it just sorts by desc if to prepend the field name "-"
public static IQueryable<t> ApplySort<t>(this IQueryable<t> source, string sort)
{
 if (source == null)
{
 throw new ArgumentNullException("source");
}

 if (sort == null)
{
 return source;
}

 var lsSort = sort.Split(',');

 // run through the sorting options and create a sort expression string from them
 completeSortExpression string = "";
 foreach (var sortOption in lsSort)
{
 // if the sort option starts with "-", we order descending, otherwise ascending
 if (sortOption.StartsWith("-"))
{
 completeSortExpression = completeSortExpression + sortOption.Remove(0, 1) + "descending";
}
else
{
 completeSortExpression = completeSortExpression + sortOption + ",";
}
}

 if (!string.IsNullOrWhiteSpace(completeSortExpression))
{
 source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
}

 return source;
 }</t></t></t>
- marietta.Ullrich3 commented on June 14th 19 at 20:55

Find more questions by tags C#ASP.NET.NETLINQ