本文介绍了从列表有条件除去N个项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一些 ASP.NET 控制,当我来到那里,我需要从列表中删除的项目,只有当他们符合一定条件的情况下。

I was writing some ASP.NET control when I came to the scenario where I needed to remove items from a list, only when they matched a certain condition.

普通的列表类的 removeall过方法做了很好的工作,但是移除的所有符合条件的predicate规定的项目。

The RemoveAll method of the generic List class does a good job, but removes all items that match the condition, specified by the predicate.

如果我只想删除一定数量的项目指定的条件是什么?你觉得是这样做的最好方法是什么?

What if I want to only remove a certain number of items specifying the condition? What do you think is the best way to do this?

推荐答案

如果你想同时指定限制的项目数,除去和条件来选择的项目删除,你可以使用这种方式:

If you want to specify both a limit for number of items to remove and a condition to select the items to remove, you can use this approach:

int limit = 30; // Suppose you want to remove 30 items at most
list.RemoveAll(item => ShouldIRemoveThis(item) && limit-- > 0);

这篇关于从列表有条件除去N个项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 05:16
查看更多