How to remove every second SortedDictionary element as quickly as possible?

I need to remove every second element from SortedDictionary as quickly as possible. Dictionary ( SortedDictionary<string, List<string>>) can contain up to 20,000 elements. So I came up with this solution:

try
{
    int loop = 0;
    while (true)
    {
        Routes.Remove(Routes.ElementAt(loop).Key);
        loop++;
    }                
}
catch
{
}

Is there an easier / better solution than this? Will a detected exception affect performance?

Edit: This seems like a better solution (see comment below):

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;

Please edit / comment if you have a better solution. Thank.

+5
source share
2 answers

I doubt it because you either need:

  • ,

  • ,

, , , SortedList, . a >

:

, . , ElementAt , linear LINQ ( ), LINQ ).

: , . , , , .
.:)

:

.:)

+6

. , . , :

int loop = 0;
lock(Routes)
{
    while (true)
    {
        try
        {
            Routes.Remove(Routes.ElementAt(loop).Key);
            loop++;
        }
        catch { break; }
    }
}

, .

0

All Articles