Take the 2-minute tour ×

Anyone know how to select a certain amount of items in a List to bind to a DataSource? Basically I'm getting back 10 items (which I don't have control over) and I only need to show 5. Originally I was thinking of using a loop and adding 5 items to a new list but that seems like a lot of code. Is there an expression that I can use to select the first 5?

//Returns a List<DataItem>
MyDataListControl.DataSource = Helper.GetDataItems(); //<= Possible expression?
share|improve this question

3 Answers 3

up vote 1 down vote accepted

You may take a look at the Skip and Take LINQ extension methods. So in your case if you wanted to take only the first 5 elements of some IEnumerable<T>:

MyDataListControl.DataSource = Helper.GetDataItems().Take(5).ToList();
share|improve this answer

What about List's GetRange method? Have you tried that? I don't the internal workings of the method; whether it also creates a new list or not.

GetRange(int index, int count)

Here is the msdn link for it.

share|improve this answer
I just checked and the efficiency of the method is O(n) where n is the count: number of elements you want, in your case 5. But since you said 'it seems like a lot of code' and you are not so worried about the time efficiency then this method reduces your code –  nbz Jan 21 '12 at 18:30

RemoveRange will probably be best as you won't have to instanciate a new list, unless that happens internally anyway.. Just make sure you're always getting 10 items or you'll potentially get an ArgumentOutOfRangeException.

list.RemoveRange(5, 5);

That should leave you with the first five items.

share|improve this answer

Your Answer


