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 |
| Published |
: 20 February 2008 |
Paul is the COO of kwiboo ltd consultant and has more than a decade of 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.