I have dynamic order by expression. I have 2 paramter, one is order by and order by direction. When I am passing orderby orderBy, orderDirec it will not work. Can you please help me, how to do order by with 2 paramter?
public async Task<IPagedList<FixedAssetDepreciationDetail>> GetDepreciationDetailAsync(int companyId, string filterText = null,
string orderBy = null, string orderDirec = "asc", int pageIndex = 0,
int pageSize = int.MaxValue, int? fixedAssetID = null)
{
var query = from a in _depreciationDetailRepository.Table
join b in _depreciationRepository.Table on a.DepreciationID equals b.ID
join c in _fixedAssetRepository.Table on a.FixedAssetID equals c.ID
where b.IsActive && !b.IsDeleted
&& a.CompanyID == companyId
&& b.CompanyID == companyId
&& (a.FixedAssetID == fixedAssetID || fixedAssetID == null)
orderby orderBy, orderDirec
select FixedAssetDepreciationDetail.Build(a, c, b);
return await query.ToPagedListAsync(pageIndex, pageSize, orderBy, orderDirec);
}
Right now, I am doing with below way, but it will not work when T.FixedAssetDepreciation.Year. T is Main class and second is child class object.
public static class IOrderQueryable
{
public static IQueryable<T> OrderByQuery<T>(this IQueryable<T> source, string dir, string sortColumn)
{
if (string.IsNullOrWhiteSpace(sortColumn))
sortColumn = "ID";
if (string.IsNullOrWhiteSpace(dir))
dir = "ASC";
Func<T, object> OrderByExp = GetOrderByExpression<T>(sortColumn);
if (OrderByExp == null)
return source;
return dir.ToUpper() == "ASC" ? source.OrderBy(OrderByExp).AsQueryable() : source.OrderByDescending(OrderByExp).AsQueryable();
}
private static Func<T, object> GetOrderByExpression<T>(string sortColumn)
{
Func<T, object> orderByExpr = null;
if (!string.IsNullOrEmpty(sortColumn))
{
Type sponsorResultType = typeof(T);
if (sponsorResultType.GetProperties().Any(prop => prop.Name == sortColumn))
{
System.Reflection.PropertyInfo pinfo = sponsorResultType.GetProperty(sortColumn);
orderByExpr = (data => pinfo.GetValue(data, null));
}
}
return orderByExpr;
}
}