2

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[:] = []
greyBow
  • 1,298
  • 3
  • 28
  • 62
  • For those who don't speak python, this assignment replaces the content of the `nav` array (or list) with the contents of the array (or list) on right hand side. So `nav[:] = []` essentially clears the array/list. – Aran-Fey Nov 07 '18 at 19:08

1 Answers1

6

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);
        }
    }
}
adjan
  • 13,371
  • 2
  • 31
  • 48