如何尽快删除 SortedDictionary 的每个第二个元素?
我必须尽快从 SortedDictionary 中删除每个第二个元素。字典 (SortedDictionary
) 最多可包含 20'000 个元素。所以我想出了这个解决方案:
try
{
int loop = 0;
while (true)
{
Routes.Remove(Routes.ElementAt(loop).Key);
loop++;
}
}
catch
{
}
还有比这更简单/更好的解决方案吗? 捕获的异常会对性能产生影响吗?
编辑:这似乎是一个更好的解决方案(请参阅下面的评论):
SortedDictionary<string, List<string>> resizedRoutes = new SortedDictionary<string, List<string>>();
bool b = true;
foreach(KeyValuePair<string, List<string>> route in Routes)
{
if(b)
{
resizedRoutes.Add(route.Key, route.Value);
b = false;
}
else
{
b = true;
}
}
Routes = resizedRoutes;
如果您有更好的解决方案,请编辑/评论。谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对此表示怀疑,因为您需要:删除项目,导致树重新平衡
将项目添加到新树,导致新树重新平衡
您无法真正避免它,但迭代它们并将它们放入
SortedList
可能会更有效如果您不会经常修改数据。是:
迭代项目,然后将所有其他项目添加到新树中,而不是修改当前树。这样,您就可以避免每次调用
ElementAt
的成本,在理想的实现中,该成本至少是对数的,而使用 LINQ 的 (这是可怕的,因为 LINQ 不知道你的树的实现)。至于例外情况:是的,它会对性能产生影响。但我不知道这与你正在做的事情有多大关系,所以它可能重要也可能不重要。
但无论哪种方式,您都不应该忽略异常。 :)
当您正在阅读时:
可能想看看函数式编程。 :)
I doubt it, because you either need to:Remove the items, causing the tree to be rebalanced
Add the items to a new tree, causing the new tree to be rebalanced
You can't really avoid it, but it might be more efficient to just iterate through them and put them in a
SortedList
if you won't be modifying the data very often.Yes:
Iterate through the items, then add every other item them to a new tree, instead of modifying the current tree. That way you'll avoid the cost of calling
ElementAt
every time, which is at least logarithmic in an ideal implementation, and linear with LINQ's (which is horrible, because LINQ has no idea about the implementation of your tree).As for the exception: Yes, it will have a performance hit. But I have no idea how much that is relative to what you're doing, so it may or may not be significant.
But either way, you should not be ignoring exceptions. :)
While you're at it:
Might want to take a look at functional programming. :)
这是一个足够好的解决方案。如果捕获到异常,它将停止从字典中删除元素。也许重新排列它,如下所示:
这将确保在删除元素时不能修改字典。
That is a good enough solution. If an exception is caught, then it will stop removing elements from the dictionary. Maybe rearrange it, like so:
This will make sure the dictionary cannot be modified while elements are being removed.