在列表上迭代时将元素添加到列表中 [英] Add elements to a list while iterating over it
问题描述
我正在尝试在列表列表上迭代时添加新元素
List< List< String> > sets = new List< List< string>>();
foreach(列表中的字符串列表)
{
foreach(X中的字符串c)
{
List< String> newSet = ir_a(列表,c,生产);
if(newSet.Count> 0)
{
sets.Add(newSet);
}
}
}
a之后出现的错误这是几个循环:
集合已修改;枚举操作可能不会执行
我知道错误是由修改列表引起的,所以我的问题是:
谢谢
您可能会用其他语言(而不是C#)来解决这个问题。他们这样做是为了避免出现不太明显的有趣的运行时行为。我更喜欢设置要添加的东西的新列表,填充它,然后将其插入循环之后。
公共类IntDoubler
{
List< int>整数
public void DoubleUp()
{
//要存储要添加的元素的列表
List< int> inserts = new List< int>();
// foreach整数,将foreach的两倍大
(整数插入值invar)加一。
{
inserts.Add(insert * 2);
}
//将新列表附加到旧的
ints.Int.AddRange(inserts);的末尾。
}
}
想象一下,如果您有一个foreach循环,并且您
希望这会有所帮助。
I'm trying to add new elements to a list of lists while iterating over it
List<List<String>> sets = new List<List<string>>();
foreach (List<String> list in sets)
{
foreach (String c in X)
{
List<String> newSet = ir_a(list, c, productions);
if (newSet.Count > 0)
{
sets.Add(newSet);
}
}
}
The error I get after a few loops is this:
Collection was modified; enumeration operation may not execute
I know the error is caused by modifying the list, so my question is: What's the best or most fancy way to sort this thing out?
Thanks
You might get away with this in other languages but not C#. They do this to avoid funny runtime behaviour that isn't obvious. I prefer to set up a new list of things you are going to add, populate it, and then insert it after the loop.
public class IntDoubler
{
List<int> ints;
public void DoubleUp()
{
//list to store elements to be added
List<int> inserts = new List<int>();
//foreach int, add one twice as large
foreach (var insert in ints)
{
inserts.Add(insert*2);
}
//attach the new list to the end of the old one
ints.AddRange(inserts);
}
}
Imagine that if you had a foreach loop, and you added an element to it each time, then it would never end!
Hope this helps.
这篇关于在列表上迭代时将元素添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!