我已经制作了一个方法,可以消除stringList中相同的任何重复.
现在,问题是它给了我这个错误:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
Run Code Online (Sandbox Code Playgroud)
我在互联网上阅读,我认为问题是我从列表foreach循环内的列表中删除一个对象.
foreach (string r in list)
{
int numberOfAppearance=0;
foreach (string rs in list)
{
if (r == rs && numberOfAppearance> 0)
list.Remove(rs);
else
numberOfAppearance++;
}
}
Run Code Online (Sandbox Code Playgroud)
我该如何修复方法?谢谢您的帮助
这是我做的:
// this is an example of my function, the string and the remover should be variables
string delimeter = ",";
string remover="4";
string[] separator = new string[] { "," };
List<String> List = "1,2,3,4,5,6".Split(separator, StringSplitOptions.None).ToList();
for (int i = 0; i < List.Count - 1; i++)
{
if(List[i]==remover)
List.RemoveAt(i);
}
string allStrings = (List.Aggregate((i, j) => i + delimeter + j));
return allStrings;
Run Code Online (Sandbox Code Playgroud)
问题是重新编译的字符串与原始字符串相同,与"1,2,3,4,5,6"相同."4"仍在其中.
怎么解决?
编辑:
解决方案是我没有检查列表中的最后一个节点,因为它在示例中看起来不像是因为它是我刚才给出的一个例子