Performs "pagination" of a sequence IEnumerable, returning a fragment ("page") of its contents. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Performs "pagination" of a sequence IEnumerable, returning a fragment ("page") of its contents.

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from   www .  j  a  v  a 2s  .com

public class Main{
        /// <summary>
    ///   <para>Performs "pagination" of a sequence, returning a fragment ("page") of its contents.</para>
    /// </summary>
    /// <typeparam name="T">Type of elements in a sequence.</typeparam>
    /// <param name="self">Source sequence from which a fragment is to be taken.</param>
    /// <param name="page">Number of fragment/slice that is to be taken. Numbering starts from 1.</param>
    /// <param name="pageSize">Size of fragment ("page"), number of entities to be taken. Must be a positive number.</param>
    /// <returns>Source that represent a fragment of the original <paramref name="self"/> sequence and consists of no more than <paramref name="pageSize"/> elements.</returns>
    /// <exception cref="ArgumentNullException">If <paramref name="self"/> is a <c>null</c> reference.</exception>
    public static IEnumerable<T> Paginate<T>(this IEnumerable<T> self, int page = 1, int pageSize = 10)
    {
      Assertion.NotNull(self);

      if (page <= 0)
      {
        page = 1;
      }

      if (pageSize <= 0)
      {
        pageSize = 10;
      }

      return self.Skip((page - 1) * pageSize).Take(pageSize);
    }
}

Related Tutorials