C#是否有类似于JavaScript中的splice
方法?
我只知道C#中的RemoveRange
,但它不会返回被移除的元素:
List<string> t = new List<string>();
t.RemoveRange(..., ...);
我希望避免编写自己的集合类。
没有确切的对应词,但你可以自己写一个:
public static List<T> Splice<T>(this List<T> source,int index,int count)
{
var items = source.GetRange(index, count);
source.RemoveRange(index,count);
return items;
}
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;
}
}
自 C# 8 版本起,你可以使用 C# Ranges。
int[] someArray = new int[5] { 1, 2, 3, 4, 5 };
int[] subArray1 = someArray[0..2]; // { 1, 2 }
int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 }
List
以实现该功能。Selman22提供了我所需要的答案。 - Michel de Nijs