Paging LINQ (tramite) Take & Skip

La prima volta che ho effettuato una paginazione funzionante non eravamo ancora nell'anno 2000 e mi ricordo l'enorme quantitativo di codice usato. Gli strumenti e le tecniche erano notevolmente diversi e non avevamo di certo a disposizione il **Paging LINQ** per renderci la vita semplice come adesso. I "giovani" non hanno idea forse di cosa voleva dire paginare (o programmare) in ASP perchè ora in .net è davvero tutto più semplice. Torniamo a noi senza troppe divagazioni? Per effettuare il Paging con Linq utilizzeremo i suoi metodi Take e Skip di cui segue la definizione.

**Nota:** Ho già scritto in passato un post simile. Si tratta di un raggruppamento per pagine (sempre tramite LINQ) per generare una lista di liste dove tutti gli elementi sono divisi in un solo colpo. Vantaggi rispetto a questo articolo? A mio avviso è utile se posso processare in parallelo le liste prodotte, mentre se devo farlo in maniera sequenziale è possibile usare Take e Skip senza troppe paturnie.

**Link:** [LINQ: Ottenere dei subset da una lista o array](https://devandreacarratta.it/linq-ottenere-subset-lista-array/)

### Paging LINQ (tramite) Take & Skip

Adesso possiamo entrare nel vivo del nostro HowTo per vedere sul campo come effettuare il nostro Paging Linq in una sola riga di codice con altre di contorno.

*Paging LINQ*
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16

public static List<dynamic> GetItems(List<dynamic> fullList, int howMany, int page)
        {
            List<dynamic> result = null;

            if (fullList != null && fullList.Count > 0)
            {
                result = fullList
                    .Skip(page * howMany)
                    .Take(howMany)
                    .ToList();
            }

            return result;
        }

Per provarlo subito vi ho scritto un esempio di come utilizzare il tutto da una Console Application in modo da vedere a video i risultati del Paging Linq appena proposto.

*DoTestLinqPaging*
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24


public static void DoTestLinqPaging(int numberOfItems, int itemsForPage)
        {
            List<dynamic> fullList = new List<dynamic>();
            for (int i = 0; i < numberOfItems; i++)
            {
                fullList.Add(i+1);
            }

            int numbersOfPage = Convert.ToInt32(numberOfItems / itemsForPage) + 1;

            for (int i = 0; i < numbersOfPage; i++)
            {
                List<dynamic> dynamics = GetItems(fullList, itemsForPage, i);

                string flatValue = string.Join('|', dynamics.ToArray());
                Console.WriteLine(flatValue);

            }
         
        }


Cosa vi dicevo all'inizio dell'articolo? Effettuare il "**Paging Linq**" è davvero semplice e richiede pochissimo codice. Provare per credere!

#### Paging LINQ : Take *Take*
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

//
// Riepilogo:
//     Returns a specified number of contiguous elements from the start of a sequence.
//
// Parametri:
//   source:
//     The sequence to return elements from.
//
//   count:
//     The number of elements to return.
//
// Parametri di tipo:
//   TSource:
//     The type of the elements of source.
//
// Valori restituiti:
//     An System.Collections.Generic.IEnumerable`1 that contains the specified number
//     of elements from the start of the input sequence.
//
// Eccezioni:
//   T:System.ArgumentNullException:
//     source is null.
public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count);

Paging LINQ : Skip

Skip

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

//
// Riepilogo:
//     Bypasses a specified number of elements in a sequence and then returns the remaining
//     elements.
//
// Parametri:
//   source:
//     An System.Collections.Generic.IEnumerable`1 to return elements from.
//
//   count:
//     The number of elements to skip before returning the remaining elements.
//
// Parametri di tipo:
//   TSource:
//     The type of the elements of source.
//
// Valori restituiti:
//     An System.Collections.Generic.IEnumerable`1 that contains the elements that occur
//     after the specified index in the input sequence.
//
// Eccezioni:
//   T:System.ArgumentNullException:
//     source is null.
public static IEnumerable<TSource> Skip<TSource>(this IEnumerable<TSource> source, int count);