Mik*_*ike 5 .net generics dictionary sorteddictionary c#-4.0
我要尽快从SortedDictionary中删除每一个元素.字典(SortedDictionary<string, List<string>>
)最多可包含20'000个元素.所以我提出了这个解决方案:
try
{
int loop = 0;
while (true)
{
Routes.Remove(Routes.ElementAt(loop).Key);
loop++;
}
}
catch
{
}
Run Code Online (Sandbox Code Playgroud)
有没有比这更简单/更好的解决方案?捕获的异常会对性能产生影响吗?
编辑:这似乎是一个更好的解决方案(见下面的评论):
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;
Run Code Online (Sandbox Code Playgroud)
如果您有更好的解决方案,请编辑/评论.谢谢.
我对此表示怀疑,因为你需要:
删除项目,导致树重新平衡
将项添加到新树,导致重新平衡新树
你无法真正避免它,但SortedList
如果你不经常修改数据,那么迭代它们并将它们放入a中可能会更有效.
遍历这些项目,然后将其他所有项目添加到新树中,而不是修改当前树.这样你就可以避免ElementAt
每次调用的成本,这在理想的实现中至少是对数的,与LINQ是线性的(这很可怕,因为LINQ不知道你的树的实现).
至于例外:是的,它会受到性能影响.但是我不知道这与你正在做的事情有多大关系,所以它可能会或者可能不会很重要.
但不管怎样,你不应该忽视例外.:)
可能想看一下函数式编程.:)