Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get items in a specific range (3 - 7) from list?

Tags:

c#

list

What would be the most efficient way to select all the items in a specific range from a list and put it in a new one?

List<DataClass> xmlList = new List<DataClass>(); 

This is my List, and I would like to put all the DataClass items between the range (3 - 7) in a new List.

What would be the most efficient way? A foreach loop that that count++ everytime untill he reaches the items between a the range and add those items to the new list?

like image 535
Niels Avatar asked Oct 30 '12 14:10

Niels


People also ask

How do you select a range in a list?

The method you are seeking is GetRange: List<int> i = new List<int>(); List<int> sublist = i. GetRange(3, 4); var filesToDelete = files. ToList().

How do I get the length of a list in C#?

Try this: Int32 length = yourList. Count; In C#, arrays have a Length property, anything implementing IList<T> (including List<T> ) will have a Count property.


2 Answers

The method you are seeking is GetRange:

List<int> i = new List<int>(); List<int> sublist = i.GetRange(3, 4);  var filesToDelete = files.ToList().GetRange(2, files.Length - 2); 

From the summary:

// Summary: //     Creates a shallow copy of a range of elements in the source System.Collections.Generic.List<T>. // Parameters: //   index: //     The zero-based System.Collections.Generic.List<T> index at which the range //     starts. //   count: //     The number of elements in the range. 
like image 140
LightStriker Avatar answered Sep 20 '22 08:09

LightStriker


If for any reason you don't like to use the GetRange method, you could also write the following using LINQ.

List<int> list = ... var subList = list.Skip(2).Take(5).ToList(); 
like image 31
Clemens Avatar answered Sep 18 '22 08:09

Clemens