thzinc

Think LINQ – .Skip() and .Take()

Needing to page through a collection is nothing new, and LINQ handles this nicely with two different methods: .Skip() and .Take(). The .Skip() method will skip over a specified number of items in an IEnumerable<>. The .Take() method will iterate over a specified number of items of an IEnumerable<> and then stop.

List<string> ordinals = new List<string> {
    "first",
    "second",
    "third",
    "fourth",
    "fifth",
    "sixth",
    "seventh",
    "eighth",
    "ninth",
    "tenth"
};

// This will contain "third", "fourth", "fifth", "sixth", "seventh", and "eighth"
var thirdThroughEighth = ordinals.Skip(2).Take(6);

What’s interesting to note is that .Skip() does not call the .Current property on the enumerator when it skips over items in an IEnumerable<>. If you are working with a List<>, this may not be a particularly interesting property of .Skip(). However, if you are using a custom enumerator that performs some extra work (object instantiation, etc.) when the .Current property is called, .Skip() will nicely never call .Current, and instead keep calling .MoveNext() until the requested number of items has been skipped over.