簡體   English   中英

從列表中排除一個項目(按索引),並取消所有其他項目

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

有一個List<int>包含一些數字。 隨機選擇一個索引,將單獨處理(稱之為索引)。 現在,我想要排除這個特定的索引,並獲取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<int> newList = items.RemoveAt(MasterIndex);

RemoveAt()從原始列表中刪除項目,因此沒有必要將集合分配給新列表。 調用RemoveAt()后, items.Contains(MasterItem)將返回false

如果性能是一個問題,您可能更喜歡使用像這樣的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倍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM