Returning the first few items from an Array list or IEnumerable collection, like T-Sql top()

I needed to bind the first 5 items in a List<T> to a repeater. Having recently discovered the .Distinct() extension, I had a look through the other methods attached to my List<T> and found .Take(int)

Basic example of using .Take()

string[] allAnimals = 
            "cat,dog,mouse,chicken,cat,dog,elephant,mouse".Split(",".ToCharArray());

foreach (string animal in allAnimals.Take(5))
{
    Console.WriteLine(animal);
}
Console.ReadLine();

The output

Only the first 5.

cat
dog
mouse
chicken
cat

Example of using .Take() when binding an IEnumerable object to a repeater

HistoricCategoriesRepeater.DataSource = allAnimals.Take(5);
HistoricCategoriesRepeater.DataBind();

You may also like to take a look at the .Skip(int) method. It can be used in conjunction with .Take() to help you with paging object data.

Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.