/// <summary> /// 转换为可分页集合(注:需要对查询接口进行排序操作,否则执行 LINQ 会抛出未排序异常)。 /// </summary> /// <typeparam name="TEntity">指定的实体类型。</typeparam> /// <param name="queryable">给定的 <see cref="IQueryable{TEntity}"/>。</param> /// <param name="computeAction">计算分页的动作。</param> /// <returns>返回 <see cref="IPageable{TEntity}"/>。</returns> public static IPageable <TEntity> AsPaging <TEntity>(this IQueryable <TEntity> queryable, Action <PagingDescriptor> computeAction) where TEntity : class { queryable.NotNull(nameof(queryable)); var descriptor = new PagingDescriptor(queryable.Count()); computeAction?.Invoke(descriptor); var q = queryable; // 跳过条数 if (descriptor.Skip > 0) { q = q.Skip(descriptor.Skip); } // 获取条数 if (descriptor.Size > 0) { q = q.Take(descriptor.Size); } return(new PagingCollection <TEntity>(q.ToList(), descriptor)); }
private static IPageable <T> AsPaging <T>(this ICollection <T>?rows, Action <PagingDescriptor> computeAction) where T : class { if (rows is null) { return(PagingCollection <T> .Empty); } var descriptor = new PagingDescriptor(rows.Count); computeAction?.Invoke(descriptor); return(new PagingCollection <T>(rows, descriptor)); }
/// <summary> /// 构造一个 <see cref="PagingCollection{T}"/>。 /// </summary> /// <param name="rows">给定的行集合。</param> /// <param name="descriptor">给定的描述符。</param> public PagingCollection(ICollection <T> rows, PagingDescriptor descriptor) { rows.NotNull(nameof(rows)); descriptor.NotNull(nameof(descriptor)); // 如果未进行分页 if (rows.Count > descriptor.Size) { // 手动内存分页 _rows = rows .Skip(descriptor.Skip) .Take(descriptor.Size) .ToList(); } else { _rows = rows; } Descriptor = descriptor; }
private PagingCollection() { _rows = Array.Empty <T>(); Descriptor = new PagingDescriptor(0); }