Readable C# equivalent of Python slice operation

The closest is really LINQ .Skip() and .Take()

Example:

var result1 = myList.Skip(2).Take(2);
var result2 = myList.Skip(1);
var result3 = myList.Take(3);
var result4 = myList.Take(3).Concat(myList.Skip(4));

As of C#8 slicing becomes a lot easier for indexed data structures.

var result1 = myList[2..5]; // end (5) is exclusive
var result2 = myList[1..^0]; // from index 1 to the end 
var result3 = myList[0..3]; // end (3) exclusive

Read more about Ranges and indices here and here.


If you have a List GetRange can come in handy.

From MSDN link:

A shallow copy of a collection of reference types, or a subset of that collection, contains only the references to the elements of the collection. The objects themselves are not copied. The references in the new list point to the same objects as the references in the original list.

The Slice function can then be:

public static IEnumerable<T> Slice<T>(this List<T> source, int from, int to) => source.GetRange(from, to - from);

Negative ranges that python slice supports can also be handled with some loss of cleanliness.