开发者

How to iterate and update a list

开发者 https://www.devze.com 2023-02-22 03:28 出处:网络
I have had this problem lots over time, if I iterate a list, and modify the list in the process it causes an exception.

I have had this problem lots over time, if I iterate a list, and modify the list in the process it causes an exception.

List<string> list = new List<string>()
                                {
                                    "one",
                                    "two",
                                    "three"
                                };

        foreach (string item in list)
        {
            if (item == "two")
            {
                list.Remove(item);
            }
        }

I have come up with my own solutions, but interested to hear your solutions.开发者_如何转开发


Well you could use linq in this case:

list = list.Where(s => s != "two").ToList();

The long way to go about it would be to build a second list of items to remove, and then iterate through that list removing items from the first list. Here is some example code:

Please note, I highly recommend going with the simple Linq solution, and not doing it this way, but if for some reason Linq is not an option for you this should work:

List<string> toRemove = new List<string>();
foreach (string item in list)
{
    if (item == "two")
    {
        toRemove.Add(item);
    }
}

foreach(string item in toRemove)
{
    list.Remove(item);
}


The answer is that you're not supposed to modify elements in a list that you're iterating over.

Also, you could do this more simply with list.Remove("two");


A simple solution involves LINQ.

var filtered = list.Where(s => s != "two").ToList();


while (list.Contains("two"))
    list.Remove("two");


Another implementation

list.ForEach(l => { if (l == "two")  list.Remove(l); });


list.RemoveAll(s => s == "two");

Note this does allow extra processing -- the "iterate" in the OP -- before returning s == "two".

0

精彩评论

暂无评论...
验证码 换一张
取 消