问题描述
我有一个元素列表,但是如果列表元素的数量大于4,我想删除所有元素,但仅将前4个保留在列表中.
I have a list of elements, however if the number of list elements is greater than 4 I want to remove all elements but leave the first 4 only in the list.
示例:
列表<>-1、2、3、4、5、6、7、8
List<> - 1, 2, 3, 4, 5, 6, 7, 8
新列表应为-1,2,3,4
The new list should be - 1,2,3,4
我正在使用List.RemoveAll(),但不确定在括号中放置什么
I am looking at using List.RemoveAll() but not sure what to put in the parentheses
期待一些帮助....
Looking forward to some help ....
史蒂芬
推荐答案
为什么不使用 c0> :
if (list.Count > 4)
{
list.RemoveRange(4, list.Count - 4);
}
(这是假设您想要突变现有列表.如果您乐于创建新序列,那么我肯定会根据亚当的建议使用list.Take(4)
,无论是否使用致电.如今,我倾向于建立查询,而不是对现有集合进行变异.)
(That's assuming you want to mutate the existing list. If you're happy creating a new sequence, I'd definitely use list.Take(4)
as per Adam's suggestion, with or without the ToList
call. These days I tend to build queries rather than mutating existing collections.)
这篇关于C#-列表-删除所有元素,但不删除前四个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!