c# - 拼接系列

标签 c# collections

在 perl 中,splice 函数从现有数组返回一个新的项目数组,同时从现有数组中删除这些项目。

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

@newarray 现在将包含来自 @oldarray 的 250 条记录,而 @oldarray 少了 250 条记录。

是否有 C# 集合类的等效项,即 Array、List、Queue、Stack,具有类似的功能?到目前为止,我只见过需要两个步骤(返回 + 删除)的解决方案。

更新 - 不存在任何功能,所以我实现了一个扩展方法来支持 Splice 功能:

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;
}

通过以下单元测试 - 成功:

[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 方法。此方法只是获取一个范围(它是列表中引用对象的副本),然后从列表中删除对象。

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;
      }
  }
}

关于c# - 拼接系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9325627/

相关文章:

collections - 比较两个列表时忽略字段

javascript - 如何在 Meteor 中取消注册集合?

c# - Caliburn.Micro 中的用户控件

c# - Ado.Net:关闭 SqlCommand 会导致关闭 DataReader

c# - WPF 中的 XMLSerialization 问题

c# - 返回 json 结果并将 null 转换为空字符串

c# - 如何在 Asp.Net Core 2.2 中将 [FromHeader] 属性与自定义模型绑定(bind)一起使用

scala - 对集合执行多次操作后返回相同的集合类型

java - 更新Map值的有效方法

vb.net: "for each"中的索引号