2014-12-31 13 views
8

有一個List<int>包含一些數字集。隨機選擇一個索引,它將被單獨處理(稱爲主文件)。現在,我想排除這個特定的索引,並獲得List的所有其他元素(稱它們爲奴隸)。從列表中排除一個項目(按索引),並取所有其他項目

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 - 任何人,怎麼樣?

編輯:無法從原始列表中刪除任何項目,否則我必須保留兩個列表。

回答

16

使用Where: -

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

工作Fiddle

+0

可愛!它完美無瑕。這種形式的「Where」在文檔中的任何地方都不明顯。 – Ajay

+0

@Ajay - 文檔在那裏,檢查我已經共享了哪裏的鏈接,Where是Where的第二個重載。 –

+2

是的。到目前爲止,我已經在實際的產品代碼中使用了這種方法(這不是明顯的整數列表)。 – Ajay

2

你可以從列表中刪除主項目,

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

RemoveAt()將刪除原列表中的項目,所以沒有必要收集分配到一個新的列表。調用RemoveAt()後,items.Contains(MasterItem)將返回false

+0

需要兩個列表。我需要保持原創! – Ajay

+1

@Ajay RemoveAt()從原始列表中刪除項目,因此沒有必要將其分配給新列表。調用RemoveAt()後,「items」中不會有主項目。 – Kurubaran

+1

那麼,你想我應該再次從數據庫,網絡,文件中讀取?這是不恰當的。 – Ajay

2

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

相關問題