Return elements between two variable indices in a list

I want to return items between two indices of variables in a list.

For example, given this list -

List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

      

I want to iterate over a list using variables for index values. Lets call index values ​​X and Y. So if X is index value 0 and Y is equal to index 5, I need to go through index 0-5 and return all the element values. X and Y can subsequently become indices from 5 to 8, for example. How would you do it?

+3


source to share


5 answers


you can use List.GetRange

var result = list.GetRange(X, Y-X+1);

      

or a simple loop



List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = X; i <= Y; i++)
{
    Console.WriteLine(list[i]);
}

      

or reinvent the wheel the way you want

public static class Extensions
{
    public static IEnumerable<T> GetRange<T>(this IList<T> list, int startIndex, int endIndex)
    {
        for (int i = startIndex; i <= endIndex; i++)
        {
            yield return list[i];
        }
    }
}

foreach(var item in list.GetRange(0, 5))
{
     Console.WriteLine(item);
}

      

+5


source


You can use Enumerable.Skip and Enumerable.Take

var res = list.Skip(noOfElementToSkip).Take(noOfElementsToTake);

      

To use a variable as indices



var res = list.Skip(x).Take(y-x+1);

      

Note You need to pass the start item index to Ignore and take the number of items you need to pass, the number of items you want in the Take parameter minus the start item number, plus one list is zero based on the index.

+6


source


int x = 0, y = 5;
List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (; x < y; x++)
{
    Console.WriteLine(list[x]);
}

      

This will work if X is always less than Y. If you don't know which is greater, add this before the loop:

 if (x > y) 
 {
      x = x ^ y;
      y = y ^ x;
      x = x ^ y;
  }

      

+2


source


Another alternative:

int X = 0, Y = 5;
Enumerable.Range(X, Y - X + 1)
.Select(index => list[index]);

      

+1


source


He has to do the trick -

        List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        int startindex = 1;
        int endIndex = 7;
        var subList = list.Skip(startindex).Take(endIndex - startindex-1).ToList();

      

+1


source







All Articles