简体   繁体   English

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

[英]Excluding one item from list (by Index), and take all others

There is a List<int> containing some set of numbers. 有一个List<int>包含一些数字。 Randomly I select an index, which will be processed separately (call it master ). 随机选择一个索引,将单独处理(称之为索引)。 Now, I want to exclude this particular index, and get all other elements of List (call them slave ). 现在,我想要排除这个特定的索引,并获取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 */

Join , Select , Except - any of them, and how? JoinSelectExcept - 其中任何一个,以及如何?

EDIT: Cannot remove any item from the original list, otherwise I have to keep two lists. 编辑:无法删除原始列表中的任何项目,否则我必须保留两个列表。

Use Where :- 使用地点 : -

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

Working Fiddle . 工作小提琴

You could remove Master item from the list, 您可以从列表中删除主项目,

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

RemoveAt() removes the item from the original list, So it's not necessary to assign the collection to a new list. RemoveAt()从原始列表中删除项目,因此没有必要将集合分配给新列表。 After calling RemoveAt(), items.Contains(MasterItem) would return false . 调用RemoveAt()后, items.Contains(MasterItem)将返回false

If performance is an issue you may prefer to use the List.CopyTo method like this. 如果性能是一个问题,您可能更喜欢使用像这样的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);
}

This implementation is almost 3 times faster than @RahulSingh answer. 这个实现几乎是@RahulSingh答案的3倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM