The Skip
extension method simply skips the given number of items. An example may be useful here and the most common usage for Skip (and Take) is with paging so that is the example I'll use.
//Get all products from database (not a realistic call here...)
var products = GetProducts();
//Page size is 25 products and we want page 2 (products 26-50)
var skipFive = letters.Skip(25);
The original list could contain 1000s of items so the UI is going to use paging. The UI wants to show 25 items at a time so the first page shows items 1-25, the second 26-50, etc. To get to page 2 we need to skip page size items from the original list so we use Skip(25)
. This skips "page 1".
Because this is IEnumerable
it isn't creating a new collection in memory but simply skipping over the existing items. Since IEnumerable
does not define how the data is stored and is forward only the implementation of Skip
is simply a foreach that ignores the first X items. The order in which items are returned is the same order as the original collection. Skip
will not modify the ordering, it just skips items.
Take
is used to limit the number of items. Most IEnumerable
methods return everything from the modified list. But if you don't need everything you can use Take
to truncate it. Going back to the paging example, since the page size is 25 we would only need to get the next 25 items. While we could return all of it that would be a waste of time. Take
will stop returning values after it reaches the desired number.
//Get the first page of items (25 page size)
var pageItems = products.Take(25);
As with Skip
it does not create anything in memory. It simply enumerates the provided collection of items until it reaches the specified limit and then it stops. The order is always defined by the underlying collection. The method will not change the ordering.
In summary, if I wanted to get page 2 of products where page size is 25 then it can be done this way.
var pageSize = 25;
var pageNumber = 2;
var skipCount = (pageNumber - 1) * pageSize;
var page2 = products.Skip(skipCount).Take(pageSize); //Get page N with given page size
If the order in which Skip
or Take
is returning items is wrong the problem is with the original collection, not the methods.