如何切片列表

时间:2017-03-14 06:27:37

标签: c# visual-studio exception exception-handling slice

好吧,我对编程很新,但我确实知道0-0 == 0.任何人都可以解释为什么我会收到这个错误?

error

我搜索过高低,无法解释这一点。我见过的切片的每个实现都是这样完成的(除了使用内置函数,我正在做的事情不允许这样做。)

3 个答案:

答案 0 :(得分:2)

这一个

new List<int>(...)

创建列表,因此那里没有索引为0的元素。

答案 1 :(得分:2)

使用扩展方法进行切片操作有一种简单的方法,请参阅下面的代码:

public static List<int> Slice(List<int> inputList, int startIndex, int endIndex)
{ 
    int elementCount = endIndex-startIndex + 1;
    return inputList.Skip(startIndex).Take(elementCount).ToList();
}

这是working example给你的。

答案 2 :(得分:1)

实施 public 方法时,添加验证概括方法:

from PyQt4.QtGui import *
import sys,threading
def window():
    app = QApplication(sys.argv)
    window = QWidget()
    btn = QPushButton()
    btn.setText("Input In Console")
    box = QFormLayout()
    box.addRow(btn)
    btn.clicked.connect(input_txt)
    window.setLayout(box)
    window.show()
    sys.exit(app.exec_())

def input_txt():
    thread = threading.Thread(target=input)
    thread.start()

if __name__ == "__main__":
    window()

所以你可以做到

//DONE: <T> - generalize - what if you want to slice, say, List<long> or List<string>?
//DONE: IEnumerable<T> - generalize: waht if you want to slice, an array, int[]? 
//DONE: we usually put public methods in Pascal case: Slice, not slice
public static List<T> Slice<T>(this IEnumerable<T> source, int startIndex, int endIndex) {
  //DONE: validation
  if (null == source)
    throw new ArgumentNullException("source");
  else if (startIndex < 0)
    throw new ArgumentOutOfRangeException("startIndex", 
      $"startIndex ({startIndex}) must be non-negative.");
  else if (startIndex > endIndex)
    throw new ArgumentOutOfRangeException("startIndex", 
      $"startIndex ({startIndex}) must not exceed endIndex ({endIndex}).");

  // Instead of pure Linq 
  // return source.Skip(startIndex).Take(endIndex - startIndex).ToList();
  // let's use a loop

  // it doesn't create endIndex - startIndex items but reserve space for them
  List<T> result = new List<T>(endIndex - startIndex);

  foreach (var item in source.Skip(startIndex))
    if (result.Count >= endIndex - startIndex)
      return result;
    else
      result.Add(item); // we add items, not put them with result[i] = ...

  // source exhausted, but we don't reach endIndex. 
  //TODO: Shall we return as is or throw an exception?
  return result;
}