有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 */
Join
,Select
,Except
- 其中任何一个,以及如何?
编辑:无法删除原始列表中的任何项目,否则我必须保留两个列表。
答案 0 :(得分:24)
答案 1 :(得分:2)
您可以从列表中删除主项目
List<int> newList = items.RemoveAt(MasterIndex);
RemoveAt()会从原始列表中删除该项目,因此没有必要将该集合分配给新列表。调用RemoveAt()后,items.Contains(MasterItem)
将返回false
。
答案 2 :(得分: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倍。