tags:

views:

81

answers:

3

I'd like pick out a List the items 5 - 10 and create a new list of the same type. Using Linq I thought of:

List<xyz> collection = new <List>();
//fill collection with lots of data
collection.AddRange( ... );

//Downsize here
var q = from e in collection select e;
q.ToArray();
List<xyz> smallcollection = new List<xyz>()
smallcollection = q.Skip(5).Take(5);

What am I doing wrong?

+4  A: 

Just var newList = q.Skip(5).Take(5).ToList()... your existing code is creating a lot of objects but not using them; the "ToArray()" is discarded, as is the "new List<xyz>()". There's also a "collection.Select(e=>e)" that does not a lot... (hidden in LINQ query syntax).

Marc Gravell
+2  A: 

Last line should be

smallcollection = q.Skip(5).Take(5).ToList();
Daniel Elliott
+1  A: 

If the original list is a List<T>, you don't need LINQ at all.

You can use the GetRange method, like this:

List<xyz> collection = new <List>();
//fill collection with lots of data
collection.AddRange( ... );


List<xyz> smallCollection = collection.GetRange(5, 5);


If it isn't a List<T>, you can use LINQ like this:

List<xyz> smallCollection = q.Skip(5).Take(5).ToList();
SLaks