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

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();

List implements a CopyTo method that lets you specify the start and number of elements to copy. I'd suggest using that.

See: http://msdn.microsoft.com/en-us/library/3eb2b9x8.aspx


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.

in c# 8 you can use Range and Index instead of Linq take and skip :

Sample array:

string[] CountryList = { "USA", "France", "Japan", "Korea", "Germany", "China", "Armenia"};  

To get this result (element 1,2,3) ==> France Japan Korea

1: Get a range of array or list:

   var NewList=CountryList[1..3]

2: Define Range object

Range range = 1..3;  
    var NewList=CountryList[range])

3: Use Index Object

Index startIndex = 1;  
Index endIndex = 3;  
var NewList=CountryList[startIndex..endIndex]

Tags:

C#

List