What is the easiest way to foreach through a List removing unwanted objects?

后端 未结 3 1095
北恋
北恋 2021-01-31 23:08

In my application, _collection is a List from which I need to remove all User objects which do not match the criteria.

However, the fol

3条回答
  •  离开以前
    2021-02-01 00:02

    Whenever there is a chance that a collection will be modified in a loop, opt for a for loop instead. The solution given by Mehrdad is lovely and definitely worth a try!

    Here's code I find helpful when dealing with modifiable collections:

    for(int index=0;index < _collection.Count; index++)
    {
        if (!_collection[index].IsApproved)
        {
            _collection.RemoveAt(index);
            index--;
        }
    }
    

提交回复
热议问题