maja
maja

Reputation: 95

Remove from dictionary and reduce other key value

I have Dictionary<string, string> where keys have value 0,1,2,3,4,etc I always have unknown number of elements. It is important to be dictionary,not list etc...

For example I have

some_dict<"0","string a">;
some_dict<"1","string b">;
some_dict<"2","string c">;
some_dict<"3","string d">;
some_dict<"4","string e">;

Now I need remove some items for some keys. For example 1 and 2 I can use remove

some_dict.remove("1");
some_dict.remove("2");

and i get :

some_dict<"0","string a">;
some_dict<"3","string d">;
some_dict<"4","string e">;

But problem is that i need reduce all of the following keys.To get something like:

some_dict<"0","string a">;
some_dict<"1","string d">;
some_dict<"2","string e">;

I was think to use for to move all strings for one place,and then remove last from dictionary.For example i need to remove key 1:

for(int i=1;i<some_dict.count();++i)
{
     some_dict[Convert.ToString(i)] = some_dict[Convert.ToString(i+1)]
}
some_dict.remove(some_dict.count()-1);

I write some similar in my app , and it is work. But what if i have 500 or more values in dictionary, will be this slow? Can i use some better method?

Upvotes: 1

Views: 1562

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

If you insist on your dictionary:

// remove whatever you want to remove, then recreate it:
some_dict = some_dict.OrderBy(kv => int.Parse(kv.Key))
    .Select((kv, index) => new { pair = kv, index })
    .ToDictionary(x => x.index.ToString(), x => x.pair.Value);

But as others commented you should consider to use a List<string> which can be used like a dictionary if you want to access items by index. You should also consider to use a Dictionary<int, string> if you want to use a dictionary.

Upvotes: 5

Related Questions