respository.GetPaged<S_Users>(out count, m => m.LoginName.Contains("a"),"LoginName asc,LoginNum desc", 1, 20);
public IList<TEntity> GetPaged<TEntity>(out int total, Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, int index = 1, int size = 20) where TEntity : class
{
int skipCount = (index - 1) * size;
var query = Get(filter, orderBy);
total = query.Count();
query = skipCount > 0 ? query.Skip(skipCount).Take(size) : query.Take(size);
return query.ToList();
}
public IList<TEntity> GetPaged<TEntity>(out int total, Expression<Func<TEntity, bool>> filter = null, string orderBy = null, int index = 1, int size = 20) where TEntity : class
{
int skipCount = (index - 1) * size;
var query = Get(filter, orderBy);
total = query.Count();
query = skipCount > 0 ? query.Skip(skipCount).Take(size) : query.Take(size);
return query.ToList();
}
public static class QueryExtensions
{
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortExpressions)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
string sortDirection = String.Empty;
string propertyName = String.Empty;
sortExpressions = sortExpressions.Trim();
string[] sorts = sortExpressions.Split(',');
for (int i = 0; i < sorts.Length; i++)
{
string sortExpression = sorts[i];
int spaceIndex = sortExpression.Trim().IndexOf(" ");
if (spaceIndex < 0)
{
propertyName = sortExpression;
sortDirection = "ASC";
}
else
{
propertyName = sortExpression.Substring(0, spaceIndex);
sortDirection = sortExpression.Substring(spaceIndex + 1).Trim();
}
if (String.IsNullOrEmpty(propertyName))
{
return source;
}
ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty);
MemberExpression property = Expression.Property(parameter, propertyName);
LambdaExpression lambda = Expression.Lambda(property, parameter);
string methodName = string.Empty;
if (i == 0)
{
methodName = (sortDirection.ToUpper() == "ASC") ? "OrderBy" : "OrderByDescending";
}
else
{
methodName = (sortDirection.ToUpper() == "ASC") ? "ThenBy" : "ThenByDescending";
}
Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName,
new Type[] { source.ElementType, property.Type },
source.Expression, Expression.Quote(lambda));
source = source.Provider.CreateQuery<T>(methodCallExpression);
}
return source;
}
}