'裁剪'c#中的列表

UpT*_*eek 2 c# collections

给定IList某种类型的Generic ,其中包含许多项目,是否有任何方法可以"裁剪"此列表,以便只保留第一个x项,其余的被丢弃?

Isa*_*avo 13

如果你可以使用Linq,那只是一个问题

// Extraact the first 5 items in myList to newList
var newList = myList.Take(5).ToList();

// You can combine with .Skip() to extract items from the middle
var newList = myList.Skip(2).Take(5).ToList();
Run Code Online (Sandbox Code Playgroud)

请注意,上面将创建包含5个元素的新列表.如果您只想迭代前5个元素,则不必创建新列表:

foreach (var oneOfTheFirstFive in myList.Take(5))
     // do stuff
Run Code Online (Sandbox Code Playgroud)


Luk*_*keH 6

现有答案创建一个新列表,其中包含原始列表中的项目子集.

如果您需要就地截断原始列表,那么这些是您的选择:

// if your list is a concrete List<T>
if (yourList.Count > newSize)
{
    yourList.RemoveRange(newSize, yourList.Count - newSize);
}

// or, if your list is an IList<T> or IList but *not* a concrete List<T>
while (yourList.Count > newSize)
{
    yourList.RemoveAt(yourList.Count - 1);
}
Run Code Online (Sandbox Code Playgroud)