【问题标题】:List slicing in C#C#中的列表切片
【发布时间】:2018-11-07 19:07:54
【问题描述】:

我在 python 脚本中遇到了这种语法,发现它被称为切片赋值。您如何在 C# 中编写此语法?

self.nav[:] = []

【问题讨论】:

  • 对于那些不会说python的人,这个赋值将nav数组(或列表)的内容替换为右侧数组(或列表)的内容。所以nav[:] = [] 基本上清除了数组/列表。

标签: c# python arrays slice


【解决方案1】:

C#没有切片赋值操作符,但是可以使用List<T>提供的方法来代替:

list[a:b] = otherList 

等价于

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

或者,在

的空间情况下
list[:] = [] 

你可以写

list.Clear();

从技术上讲,您可以编写自己的列表类,它继承自 List<T> 并模拟 python 的行为(至少部分):

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

【讨论】:

  • Python 确实开始和结束索引。 RemoveRange 方法采用起始索引和计数,而不是结束索引。
  • @juharr 解决了这个问题
  • 另外我认为特例是list[:] = []
  • 那么self.nav[:] = []等价于nav.Clear(),只是清空列表?
猜你喜欢
  • 2010-12-14
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多