我已经制作了一个方法,可以消除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)
我该如何修复方法?谢谢您的帮助
首先,正如评论中所述,LINQ已经为您介绍了这一点:
list = list.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)
这也值得探讨LINQ数据操作-它可以让事情变得更简单.
至于你当前的代码有什么问题 - 有几件事:
首先,你是按项而不是索引删除,这将删除该项的第一次出现,而不是你实际看到的那一项
其次,如果您在迭代时修改列表,您将获得您所看到的异常.来自以下文档List<T>.GetEnumerator:
只要集合保持不变,枚举器仍然有效.如果对集合进行了更改(例如添加,修改或删除元素),则枚举数将无法恢复,并且其行为未定义.
您可以通过索引迭代而不是使用foreach循环来解决这个问题,但是如果要删除项目,则需要记住下面的所有内容都会向上移动一个元素.因此,您需要向后迭代以删除项目,或者您需要记住减少索引.
这是一种方法,它根据我们正在查看的内容使用索引向前迭代,但在查找重复项时使用向后 - 当我们到达我们正在查看的索引时停止.请注意,这仍然是O(N 2) - 它不如使用效率高Distinct:
// We're looking for duplicates *after* list[i], so we don't need to go as far
// as i being the very last element: there aren't any elements after it to be
// duplicates. (We could easily still just use list.Count, and the loop for j
// would just have 0 iterations.)
for (int i = 0; i < list.Count - 1; i++)
{
// Go backwards from the end, looking for duplicates of list[i]
for (int j = list.Count - 1; j > i; j--)
{
if (list[j] == list[i])
{
list.RemoveAt(j);
}
}
}
Run Code Online (Sandbox Code Playgroud)
(有关详细信息Distinct,请参阅我的Edulinq帖子.)
| 归档时间: |
|
| 查看次数: |
954 次 |
| 最近记录: |