Site icon .Netitude

C# equivalent of Python’s list slicing (list[:])

UPDATE: C# has introduced Range Expressions as of C# 8. Check them out instead!

While porting some Python code, I wanted to make it as close of a match as possible so I came up with this extension method.

Enjoy.

MSTest:

   1: [TestMethod]
   2: public void TestSlicing()
   3: {
   4:     var numbers = new[] { 0, 1, 2, 3, 4, 5, 6, 7 };
   5:     var sliced = numbers.Slice(-3, -1);
   6:     Assert.AreEqual(2, sliced.Count());
   7:     Assert.AreEqual(5, sliced.ElementAt(0));
   8:     Assert.AreEqual(6, sliced.ElementAt(1));
   9:
  10:     sliced = numbers.Slice(1, 4);
  11:     Assert.AreEqual(3, sliced.Count());
  12:     Assert.AreEqual(1, sliced.ElementAt(0));
  13:     Assert.AreEqual(2, sliced.ElementAt(1));
  14:     Assert.AreEqual(3, sliced.ElementAt(2));
  15:
  16:     sliced = numbers.Slice(-3);
  17:     Assert.AreEqual(3, sliced.Count());
  18:     Assert.AreEqual(5, sliced.ElementAt(0));
  19:     Assert.AreEqual(6, sliced.ElementAt(1));
  20:     Assert.AreEqual(7, sliced.ElementAt(2));
  21:
  22:     sliced = numbers.Slice(null, -2);
  23:     Assert.AreEqual(6, sliced.Count());
  24:     Assert.AreEqual(0, sliced.ElementAt(0));
  25:     Assert.AreEqual(1, sliced.ElementAt(1));
  26:     Assert.AreEqual(2, sliced.ElementAt(2));
  27:
  28:     sliced = numbers.Slice(null, 3);
  29:     Assert.AreEqual(3, sliced.Count());
  30:     Assert.AreEqual(0, sliced.ElementAt(0));
  31:     Assert.AreEqual(1, sliced.ElementAt(1));
  32:     Assert.AreEqual(2, sliced.ElementAt(2));
  33:
  34:     sliced = numbers.Slice(4);
  35:     Assert.AreEqual(4, sliced.Count());
  36:     Assert.AreEqual(4, sliced.ElementAt(0));
  37:     Assert.AreEqual(5, sliced.ElementAt(1));
  38:     Assert.AreEqual(6, sliced.ElementAt(2));
  39: }
Exit mobile version