How delete items from Dictionary

ⅰ亾dé卋堺 提交于 2020-01-03 06:34:29

问题


I have

   Dictionary<string, List<string>> Dic = new Dictionary<string, List<string>>();

How delete first 1,2,3 elements From Dic. I dont know how make it with "foreach"

foreach (KeyValuePair<string, List<string>> kvPair in Dic)
            {
                Console.WriteLine(kvPair.Key);
                foreach (string str in kvPair.Value)
                {

                }
            }

回答1:


You can't get item 1,2,3 from the dictionary, you can only remove on the basis of a key.

Dictionary MSDN

The order in which the items are returned is undefined.

You may use Orderby to sort the dictionary on the basis of a key. But to remove an item from the dictionary you will need the key.

See Dictionary.Remove

EDIT: based on your edited question with "foreach"

You can't modify the dictionary while enumerating on it. If you try removing items from the dictionary in the foreach you will get error:

Collection was modified; enumeration operation may not execute.

You may convert the dictionary to an array and then remove the items from the dictionary (something like below, it may be improved or changed, it is just for an idea):

        var dicArrray = Dic.ToArray();
        foreach (KeyValuePair<string, List<string>> kvPair in dicArrray)
        {
            if (kvPair.Key.Equals("1"))
                Dic.Remove(kvPair.Key);
        }

But remember, the order in which the items will be in array is undefined. You can't be sure about it




回答2:


as habib says you can not delete item from dictionary based upon index, you can only remove item based upon the key, use Remove() method

read more from here- Remove Item in Dictionary based on Value




回答3:


first, create a collection of keys you want to remove:

var toDelete = new List<string>();
int count = 3;
foreach(var pair in dictionary) {
    toDelete.Add(pair.Key);
    count -= 1;
    if( count==0 ) break;
}

// then when ready - delete
foreach(string key in toDelete) dictionary.Remove(key);

the reason is not to invalidate dictionary enumerator by removing items while enumerating.

also consider that order in which key pairs appear is not explicitly set in specification, so you may not rely on it - even if it works now it may stop working in a next version of framework. Thus you have also to decide what does "first 3" means before creating a list of elements to delete.




回答4:


To remove an item in a dictionary, use the Remove() method. For example:

Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
dictionary.Add("1", new List<string());
dictionary.Remove("1");

The order dictionary elements are added is not maintained. However, if you want to delete the highest key, for example, do something like:

dictionary.Remove(dictionary.Keys.OrderBy().First());



回答5:


If dic is a "simple" Dictionary, using LINQ you can create a new dictionary from the original and reassign it to dic, like this:

dic = dic.Skip(3).ToDictionary(kv => kv.Key, kv => kv.Value);

As pointed out by astander in a comment and in Habib's answer, the order of the dictionary items is undefined, so you might want to apply this technique on a SortedDictionary only.

In that case, you would need to create a new SortedDictionary from the LINQ result:

dic = new SortedDictionary<string, List<string>>(
          dic.Skip(3).ToDictionary(kv => kv.Key, kv => kv.Value));


来源:https://stackoverflow.com/questions/12312240/how-delete-items-from-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!