#190 : Application d'une méthode générique pour la pagination.
This commit is contained in:
56
Webzine.Repository/RepositoryPaginationExtensions.cs
Normal file
56
Webzine.Repository/RepositoryPaginationExtensions.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
namespace Webzine.Repository;
|
||||
|
||||
/// <summary>
|
||||
/// Fournit des méthodes génériques pour paginer des collections dans la couche Repository.
|
||||
/// </summary>
|
||||
public static class RepositoryPaginationExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Retourne une portion paginée d'une requête.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type des éléments paginés.</typeparam>
|
||||
/// <param name="source">Source à paginer.</param>
|
||||
/// <param name="offset">Nombre d'éléments à ignorer.</param>
|
||||
/// <param name="limit">Nombre maximal d'éléments à retourner.</param>
|
||||
/// <returns>La requête paginée.</returns>
|
||||
public static IQueryable<T> Paginate<T>(this IQueryable<T> source, int offset, int limit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ValidatePaginationArguments(offset, limit);
|
||||
|
||||
return source
|
||||
.Skip(offset)
|
||||
.Take(limit);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retourne une portion paginée d'une collection en mémoire.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Type des éléments paginés.</typeparam>
|
||||
/// <param name="source">Source à paginer.</param>
|
||||
/// <param name="offset">Nombre d'éléments à ignorer.</param>
|
||||
/// <param name="limit">Nombre maximal d'éléments à retourner.</param>
|
||||
/// <returns>La collection paginée.</returns>
|
||||
public static IEnumerable<T> Paginate<T>(this IEnumerable<T> source, int offset, int limit)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ValidatePaginationArguments(offset, limit);
|
||||
|
||||
return source
|
||||
.Skip(offset)
|
||||
.Take(limit);
|
||||
}
|
||||
|
||||
private static void ValidatePaginationArguments(int offset, int limit)
|
||||
{
|
||||
if (offset < 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(offset), "L'offset doit être supérieur ou égal à 0.");
|
||||
}
|
||||
|
||||
if (limit <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(limit), "La limite doit être strictement supérieure à 0.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user