I am writing a c# program where I have the following method. I see that I am writing the same code many a times in this method. I am not able to break the code into reusable pieces. Can somebody take a look at it and suggest ?
private static IOrderedQueryable<T> FormatQuery<T>(IQueryable<T> query, Expression property, ParameterExpression sortParam, SortFilter sortFilter, ref IOrderedQueryable<T> orderedQuery)
{
if (property.Type == typeof(int))
{
var sortExpr = Expression.Lambda<Func<T, int>>(property, new[] { sortParam });
orderedQuery = !sortFilter.IsDescending
? (orderedQuery == null ? query.OrderBy(sortExpr) : orderedQuery.ThenBy(sortExpr))
: (orderedQuery == null ? query.OrderByDescending(sortExpr) : orderedQuery.ThenByDescending(sortExpr));
}
else if (property.Type == typeof(bool))
{
var sortExpr = Expression.Lambda<Func<T, bool>>(property, new[] { sortParam });
orderedQuery = !sortFilter.IsDescending
? (orderedQuery == null ? query.OrderBy(sortExpr) : orderedQuery.ThenBy(sortExpr))
: (orderedQuery == null ? query.OrderByDescending(sortExpr) : orderedQuery.ThenByDescending(sortExpr));
}
else if (property.Type == typeof(DateTimeOffset?))
{
var sortExpr = Expression.Lambda<Func<T, DateTimeOffset>>(
Expression.Coalesce(property, Expression.Constant(DateTimeOffset.MaxValue)), new[] { sortParam });
orderedQuery = !sortFilter.IsDescending
? (orderedQuery == null ? query.OrderBy(sortExpr) : orderedQuery.ThenBy(sortExpr))
: (orderedQuery == null ? query.OrderByDescending(sortExpr) : orderedQuery.ThenByDescending(sortExpr));
}
else
{
var sortExpr = Expression.Lambda<Func<T, object>>(property, new[] { sortParam });
orderedQuery = !sortFilter.IsDescending
? (orderedQuery == null ? query.OrderBy(sortExpr) : orderedQuery.ThenBy(sortExpr))
: (orderedQuery == null ? query.OrderByDescending(sortExpr) : orderedQuery.ThenByDescending(sortExpr));
}
return orderedQuery;
}
Thanks in advance.
Make property a
<T2>
instead ofExpression
and put<T, T2>
before the params, after the parameters parenthesys you can putwhere T2 : Expression
, now u can just use T2 for properties type, sorry i will write more when i get home i am doing this from cell phoneEDIT: Ok home now so check this out: