Association of collections

In perl, the splice function returns a new array of elements from an existing array and at the same time removes these elements from the existing array.

my @newarry = splice @oldarray, 0, 250;

@newarraywill now contain 250 entries from @oldarrayand @oldarrayless than 250 entries.

Is there an equivalent for C # collection classes like Array, List, Queue, Stack with a similar function? So far I have seen solutions where two steps are required (return + remove).

Update - no functionality, so I applied the extensio method to support the Splice function:

public static List<T>Splice<T>(this List<T> Source, int Start, int Size) 
{
  List<T> retVal = Source.Skip(Start).Take(Size).ToList<T>();
  Source.RemoveRange(Start, Size);
  return retVal;
}

With the following Unit test - which succeeds:

[TestClass]
public class ListTest
{
  [TestMethod]
  public void ListsSplice()
  {
    var lst = new List<string>() {
      "one",
      "two",
      "three",
      "four",
      "five"
    };

    var newList = lst.Splice(0, 2);

    Assert.AreEqual(newList.Count, 2);
    Assert.AreEqual(lst.Count, 3);

    Assert.AreEqual(newList[0], "one");
    Assert.AreEqual(newList[1], "two");

    Assert.AreEqual(lst[0], "three");
    Assert.AreEqual(lst[1], "four");
    Assert.AreEqual(lst[2], "five");

  }
}
+5
source share
3 answers

Splice . ( ), .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SpliceExample
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            List<int> subset = numbers.Splice(3, 3);

            Console.WriteLine(String.Join(", ", numbers)); // Prints 1, 2, 3, 7, 8, 9
            Console.WriteLine(String.Join(", ", subset));  // Prints 4, 5, 6

            Console.ReadLine();
        }
    }

  static class MyExtensions
  {
      public static List<T> Splice<T>(this List<T> list, int index, int count)
      {
          List<T> range = list.GetRange(index, count);
          list.RemoveRange(index, count);
          return range;
      }
  }
}
+3

Stack.Pop() Queue.Dequeue(), , .

, , , , . , , , , , .

0

, , GetRange() RemoveRange() . Skip() Take() :

    public static class ListExtension
    {
      public static List<T> Splice<T>(this List<T> source, int start, int size)
      {
          var items = source.Skip(start).Take(size).ToList<T>(); 
          if (source.Count >= size)
              source.RemoveRange(start, size);
          else 
              source.Clear();
          return items;
      }
    }
0

All Articles