Modifying list inside foreach loop

后端 未结 3 1438
暖寄归人
暖寄归人 2021-01-01 16:51

I have a construction similar to this (but a lot more complicated):

var list = new List();

// .. populate list ..

foreach(var item i         


        
3条回答
  •  自闭症患者
    2021-01-01 17:39

    It's hard to offer useful advice without knowing what kinds of edits are being made. The pattern that I've found is has the most general-purpose value, though, to just construct a new list.

    For example, if you need to look at each item and decide between removing it, leaving it as-is, or inserting items after it, you could use a pattern like this:

    IEnumerable butcherTheList(IEnumerable input)
    {
        foreach (string current in input)
        {
            if(case1(current))  
            {
                yield return current;
            }
            else if(case2(current))
            {
                yield return current;
                yield return someFunc(current);
            }
            // default behavior is to yield nothing, effectively removing the item
        }
    }
    
    List newList = butcherTheList(input).ToList();
    

提交回复
热议问题