c# equivalent of splitting a list [x-12:x]

I have a list of monthly values which I want to get a rolling yearly list over every iteration. In python, I can easily do this using something like

tempList = origList[x-12:x] 

Where x is the iterator. How can this be achieved using c#?

>Solution :

You can achieve that using the List<T>.GetRange method.

List<int> tempList = origList.GetRange(x - 12, 12);

The first argument is the index of the first element to include in the range. The second argument is the number of elements to include in the range.

As pointed from the comment section. You can also use the range operator.

int[] tempArray = origArray[(x-12)..^x];

Leave a Reply