In perl, the splice function returns a new array of items from an existing array and at the same time removes these items from the existing array.
my @newarry = splice @oldarray, 0, 250;
@newarray
will now contain 250 records from @oldarray
and @oldarray
is 250 records less.
Is there an equivalent for the C# collection classes ie Array, List, Queue, Stack with a similar function? So far I have only seen solutions where two steps are required (return + remove).
Update - no functionality exists so I have implemented an 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");
}
}
Splice Sounds samples are completely royalty-free, which means you can incorporate them in your own compositions and recordings without any further clearance or royalty obligations.
Is Splice Worth it? (Quick Answer) Splice is worth it for beatmakers. For as little as $7.99/month, you get 100 credits to use on samples and presets, as well as unlimited cloud storage to back up your projects. If you want fresh, high-quality samples from popular producers – get Splice.
You have a royalty-free license for every sound that you download from Splice Sounds.
You can implement a Splice method with an extension. This method simply get a range (which is a copy of the referenced object in the list), then it removes the objects from the list.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With