List slicing in C#

Viewed 2655

I came across this syntax in a python script and saw that it is called a slice assignment. How do you write this syntax in C#?

self.nav[:] = []
1 Answers

C# does not have a slicing assignment operator, but you can use the methods provided by List<T> instead:

list[a:b] = otherList 

is equivalent to

list.RemoveRange(a,b-a);
list.InsertRange(a, otherList);

Or, in the spacial case of

list[:] = [] 

you can just write

list.Clear();

Technically, you could write your own list class that inherits from List<T> and emulates pythons behavior (at least partly):

public class ExtendedList<T> : List<T> 
{
    public IEnumerable<T> this[int start, int end] 
    {
        get 
        { 
            return this.Skip(start).Take(end - start); 
        }
        set 
        {
            int num = end - start;
            RemoveRange(start, Count - num > 0 ? num : 0);
            InsertRange(start, value);
        }
    }
}
Related