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?
source to share
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);
}
source to share
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.
source to share
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;
}