【问题标题】:Excluding one item from list (by Index), and take all others从列表中排除一项(按索引),并获取所有其他项
【发布时间】:2015-02-27 10:25:51
【问题描述】:

有一个 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 - 任何一个,以及如何?

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

【问题讨论】:

  • 我知道这是一个老问题,但可能值得考虑替换“主”和“从”这两个词——由于它们与奴隶制。一些建议的替代方案:en.wikipedia.org/wiki/Master/…
  • 公平点@Lou

标签: c# .net linq list enumerable


【解决方案1】:

使用Where:-

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

工作Fiddle

【讨论】:

  • 可爱!它完美无缺。这种Where 形式在文档中的任何地方都不明显。
  • @Ajay - 文档在那里,检查我为Where 共享的链接,这是 Where 的第二个重载。
  • 是的。到这个时候,我已经在实际的产品代码中使用了这种方法(这显然不是整数列表)。
【解决方案2】:

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

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

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

【讨论】:

  • 需要两个列表。我要保持原创!
  • @Ajay RemoveAt() 从原始列表中删除该项目,因此没有必要将其分配给新列表。调用 RemoveAt() 后,“项目”中将没有主项目。
  • 那么,您希望我再次读取数据库、网络、文件吗?这不合适。
  • @Ajay 刚刚看到您不想从原始列表中删除项目的编辑。
【解决方案3】:

如果性能是一个问题,您可能更喜欢像这样使用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 倍。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2020-06-08
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多