K_M
K_M

Reputation: 386

Return elements between two variable indexes in a list

I want to return elements between two variable indexes 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 loop through the list using to variables for index values. Let’s call the index values X and Y. So if X equals an index value of 0 and Y equals a value of 5, I need to loop through the index 0-5 and return all of the element values. X and Y could later become index values of 5 through 8 for example. How would I accomplish this?

Upvotes: 4

Views: 5153

Answers (5)

Adil
Adil

Reputation: 148110

You can use Enumerable.Skip and Enumerable.Take

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

To using variable as indexes

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

Note You need to pass the start element index to Skip and for taking number of elements you need to pass number of element you want in Take parameter minus the start element number, plus one list is zero-based index.

Upvotes: 6

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

you can use List.GetRange

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

or a simple for 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 reinventing 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);
}

Upvotes: 5

Yogi
Yogi

Reputation: 9739

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

Upvotes: 1

Dennis_E
Dennis_E

Reputation: 8894

Another alternative:

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

Upvotes: 2

user2730989
user2730989

Reputation:

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 would work if X is always smaller than Y. If you don't know which is bigger add this before the loop:

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

Upvotes: 2

Related Questions