1

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
  • 4
    Please note from msdn.microsoft.com/en-us/library/xfhwa508.aspx For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey, TValue> structure representing a value and its key. The order in which the items are returned is undefined Sep 7, 2012 at 5:34

5 Answers 5

12

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

1

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

1

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.

2
  • Your first 7 lines are a long way of writing var toDelete = dictionary.Keys.Take(3).ToList()
    – Jon Skeet
    Sep 7, 2012 at 5:47
  • I am well aware of that, but the question suggests simpler syntax.
    – aiodintsov
    Sep 7, 2012 at 5:48
0

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());
4
  • @RadzhabAhvahsky: You'd have to give more specific detail about what you mean before we could answer that question.
    – Jon Skeet
    Sep 7, 2012 at 5:48
  • @RadzhabAhvahsky You can only use for with arrays because the index is always an integer. Dictionaries can use other types as indexes. You can use foreach on the Keys and Values properties or the dictionary itself with a KeyPair<TKey, TValue>, however.
    – akton
    Sep 7, 2012 at 5:48
  • 1
    @akton: Well you can use for with dictionaries. For example: for (var iterator = dictionary.GetEnumerator(); iterator.MoveNext(); ). This would unfortunately not dispose of the enumerator, of course. But basically, for loops aren't limited to integers - although that's probably what the OP was thinking of. That's why I asked for more detail :)
    – Jon Skeet
    Sep 7, 2012 at 5:50
  • @JonSkeet Good point. I assumed that's what RadzhabAhvahsky was asking but should have stepped back.
    – akton
    Sep 7, 2012 at 5:53
0

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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.