We often need to apply pagination on a data source. A simple way to do that using
LINQ is to apply Skip and Take successively as follows:
myCustomers.Skip(2).Take(3); //This should ignore the first 2 and return the next 3 customers from the sequence
However, if you're using Entity Framework, beware. This will throw a System.NotSupportedException
with the following message:
The method 'Skip' is only supported for sorted input in LINQ to Entities. The method
'OrderBy' must be called before the method 'Skip'.
The reason is, LINQ to Entities does not support the Skip operator on sequences that
are not ordered. So we have to either apply OrderBy or OrderByDescending on the
sequence before applying Skip.
We can avoid the error If we do something like the following:
myCustomers.OrderBy(c => c.CustomerId).Skip(2).Take(3);