Readable C# equivalent of Python slice operation

LJNielsenDk picture LJNielsenDk · Dec 19, 2013 · Viewed 24.8k times · Source

What is the C# equivalent of Python slice operations?

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
result1 = my_list[2:4]
result2 = my_list[1:]
result3 = my_list[:3]
result4 = my_list[:3] + my_list[4:]

Some of it is covered here, but it is ugly and doesn't address all the uses of slicing to the point of it not obviously answering the question.

Answer

Ben picture Ben · Dec 19, 2013

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));