QueryableExtensions.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4. using Abp.Application.Services.Dto;
  5. namespace Abp.Linq.Extensions
  6. {
  7. /// <summary>
  8. /// Some useful extension methods for <see cref="IQueryable{T}"/>.
  9. /// </summary>
  10. public static class QueryableExtensions
  11. {
  12. /// <summary>
  13. /// Used for paging. Can be used as an alternative to Skip(...).Take(...) chaining.
  14. /// </summary>
  15. public static IQueryable<T> PageBy<T>(this IQueryable<T> query, int skipCount, int maxResultCount)
  16. {
  17. if (query == null)
  18. {
  19. throw new ArgumentNullException("query");
  20. }
  21. return query.Skip(skipCount).Take(maxResultCount);
  22. }
  23. /// <summary>
  24. /// Used for paging with an <see cref="IPagedResultRequest"/> object.
  25. /// </summary>
  26. /// <param name="query">Queryable to apply paging</param>
  27. /// <param name="pagedResultRequest">An object implements <see cref="IPagedResultRequest"/> interface</param>
  28. public static IQueryable<T> PageBy<T>(this IQueryable<T> query, IPagedResultRequest pagedResultRequest)
  29. {
  30. return query.PageBy(pagedResultRequest.SkipCount, pagedResultRequest.MaxResultCount);
  31. }
  32. /// <summary>
  33. /// Filters a <see cref="IQueryable{T}"/> by given predicate if given condition is true.
  34. /// </summary>
  35. /// <param name="query">Queryable to apply filtering</param>
  36. /// <param name="condition">A boolean value</param>
  37. /// <param name="predicate">Predicate to filter the query</param>
  38. /// <returns>Filtered or not filtered query based on <paramref name="condition"/></returns>
  39. public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, bool>> predicate)
  40. {
  41. return condition
  42. ? query.Where(predicate)
  43. : query;
  44. }
  45. /// <summary>
  46. /// Filters a <see cref="IQueryable{T}"/> by given predicate if given condition is true.
  47. /// </summary>
  48. /// <param name="query">Queryable to apply filtering</param>
  49. /// <param name="condition">A boolean value</param>
  50. /// <param name="predicate">Predicate to filter the query</param>
  51. /// <returns>Filtered or not filtered query based on <paramref name="condition"/></returns>
  52. public static IQueryable<T> WhereIf<T>(this IQueryable<T> query, bool condition, Expression<Func<T, int, bool>> predicate)
  53. {
  54. return condition
  55. ? query.Where(predicate)
  56. : query;
  57. }
  58. }
  59. }