Exclude one item from the list (by index) and accept all the rest

There is a List<int> containing some set of numbers. By chance, I choose an index that will be processed separately (let's call it a master). Now I want to exclude this specific index and get all the other List elements (call them subordinates).

 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?

EDIT: It is not possible to remove any item from the original list, otherwise I have to save the two lists.

+8
list c # linq enumerable
source share
3 answers

Use Where : -

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

Fiddle work.

+16
source share

You can remove the main item from the list,

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

RemoveAt () removes the item from the original list, so there is no need to assign a collection to a new list. After calling RemoveAt (), items.Contains(MasterItem) will return false .

+2
source share

If performance is a problem, you can use the List.CopyTo method like this.

 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's answer.

+2
source share

All Articles