简体   繁体   English

我可以改善这些分页扩展方法吗?

[英]Can I improve these Pagination extension methods?

I've just written a couple of pagination extension methods and I was curious to know if there was any improvements I could make. 我刚刚编写了几种分页扩展方法,但我很想知道是否可以进行任何改进。

I'm pretty happy with the base pagination method, where you supply both the page size and page number (as seen below) 我对基本的分页方法非常满意,您可以在其中提供页面大小和页码(如下所示)

    public static IEnumerable<T> Paginate<T>(this IEnumerable<T> source, int pageSize, int pageNumber)
    {
        if (pageSize == 0) throw new ArgumentOutOfRangeException("pageSize");
        if (pageNumber == 0) throw new ArgumentOutOfRangeException("pageNumber");

        return source.Skip(pageSize * (pageNumber - 1)).Take(pageSize);
    }

but I was wondering if there was a better way to do the "auto" pagination, where it returns a IEnumerable<IEnumerable<T>> 但我想知道是否有更好的方法可以执行“自动”分页,它会返回IEnumerable<IEnumerable<T>>

    public static IEnumerable<IEnumerable<T>> Paginate<T>(this IEnumerable<T> source, int pageSize)
    {
        source.ThrowIfNull("source");
        if (pageSize == 0) throw new ArgumentOutOfRangeException("pageSize");

        var pageCount = (int)Math.Ceiling(source.Count() / (double)pageSize);

        if (pageSize == 1)
            pageCount = source.Count();

        for (int i = 1; i <= pageCount; i++)
        {
            yield return source.Paginate(pageSize, i);
        }
    }

It seems a bit suspect to have to iterate twice (once for the count and once for the yield return. 似乎有点怀疑必须迭代两次(一次用于计数,一次用于收益率返回)。

Is there any obvious way I could improve these methods? 有什么明显的方法可以改善这些方法?

Take a look at MoreLinq Batch :- http://code.google.com/p/morelinq/source/browse/trunk/MoreLinq/Batch.cs?r=84 看看MoreLinq Batch:-http: //code.google.com/p/morelinq/source/browse/trunk/MoreLinq/Batch.cs? r=84

Which is implemented as: 实现为:

public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(
              this IEnumerable<TSource> source, int size)
{
  TSource[] bucket = null;
  var count = 0;

  foreach (var item in source)
  {
      if (bucket == null)
          bucket = new TSource[size];

      bucket[count++] = item;
      if (count != size)
          continue;

      yield return bucket;

      bucket = null;
      count = 0;
  }

  if (bucket != null && count > 0)
      yield return bucket.Take(count);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM