从列表中排除一个项目(按索引),并获取所有其他项目

本文关键字:项目 其他 索引 获取 一个 列表 排除 | 更新日期: 2023-09-27 18:35:56

有一个包含一组数字的List<int>。我随机选择一个索引,该索引将单独处理(称为 master)。现在,我想排除这个特定的索引,并获取List的所有其他元素(称它们为 slave)。

var items = new List<int> { 55, 66, 77, 88, 99 };
int MasterIndex = new Random().Next(0, items .Count);
var master = items.Skip(MasterIndex).First();
// How to get the other items into another List<int> now? 
/*  -- items.Join;
    -- items.Select;
    -- items.Except */

JoinSelectExcept - 其中任何一个,以及如何?

编辑:无法从原始列表中删除任何项目,否则我必须保留两个列表。

从列表中排除一个项目(按索引),并获取所有其他项目

使用位置:-

var result = numbers.Where((v, i) => i != MasterIndex).ToList();

工作小提琴。

如果性能是一个问题,您可能更喜欢使用 List.CopyTo 方法,如下所示。

List<T> RemoveOneItem1<T>(List<T> list, int index)
{
    var listCount = list.Count;
    // Create an array to store the data.
    var result = new T[listCount - 1];
    // Copy element before the index.
    list.CopyTo(0, result, 0, index);
    // Copy element after the index.
    list.CopyTo(index + 1, result, index, listCount - 1 - index);
    return new List<T>(result);
}

此实现几乎比@RahulSingh答案快 3 倍。

您可以从列表中删除主项目,

List<int> newList = items.RemoveAt(MasterIndex);

RemoveAt() 从原始列表中删除该项,因此无需将集合分配给新列表。调用 RemoveAt() 后,items.Contains(MasterItem) 将返回 false