Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return elements between two variable indexes in a list

Tags:

c#

.net

list

linq

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?

like image 846
Kevin Moore Avatar asked Dec 05 '22 21:12

Kevin Moore


2 Answers

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.

like image 63
Adil Avatar answered Dec 08 '22 09:12

Adil


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);
}
like image 41
Hamid Pourjam Avatar answered Dec 08 '22 11:12

Hamid Pourjam