I have multiple line condition for order by as below
if (enum1)
{
var = itemlist.orderby(r => r.column1)
}
else if (emum2)
{
var = itemlist.orderby(r => r.column2)
}
And so on.. Any way to do such thing dynamically.
I have multiple line condition for order by as below
if (enum1)
{
var = itemlist.orderby(r => r.column1)
}
else if (emum2)
{
var = itemlist.orderby(r => r.column2)
}
And so on.. Any way to do such thing dynamically.
What you can do is to better manage the column selection for sorting, e.g. using some collection that holds the Func<> for KeySelector.
E.g. if you have a class name 'SomeDTO' with four properties, Prop1,2,3 and 4. And four corresponding enum members.
var searchByMapping = new Dictionary<SearchByEnum,Func<SomeDTO, object>>();
searchByMapping.Add(SearchByEnum.Prop1, x => x.Prop1);
searchByMapping.Add(SearchByEnum.Prop2, x => x.Prop2);
searchByMapping.Add(SearchByEnum.Prop3, x => x.Prop3);
coll = coll.OrderBy(searchByMapping[searchByEnumParam]).ToList();
This is a not so dynamic approach but a typesafe one.
Supposing your enum can have only two values : enum yourEnum( X=0, Y}
enum1 was somewhere set:
itemlist = enum1==Enum.X? itemlist.Orderby(r => r.column1): itemlist.Orderby(r => r.column2)
I did using below extension method.
public static class IQueryableExtensions
{
public static IQueryable<T> OrderBy<T>(this IQueryable<T> items, string propertyName)
{
var typeOfT = typeof(T);
var parameter = Expression.Parameter(typeOfT, "parameter");
var propertyType = typeOfT.GetProperty(propertyName).PropertyType;
var propertyAccess = Expression.PropertyOrField(parameter, propertyName);
var orderExpression = Expression.Lambda(propertyAccess, parameter);
var expression = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { typeOfT, propertyType }, items.Expression, Expression.Quote(orderExpression));
return items.Provider.CreateQuery<T>(expression);
}
}