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

后端 未结 3 1094
北恋
北恋 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-01-31 23:55

    You can always start at the top index and iterate downward towards 0:

    for (int i = _collection.Count - 1; i >= 0; i--)
    {
        User user = _collection[i];
        if (!user.IsApproved())
        {
            _collection.RemoveAt(i);
        }
    }
    

    Mehrdad's answer looks pretty darn elegant, though.

提交回复
热议问题