How to effectively fix the number of entries in the dictionary?

I had List<myClass> myList

to store a list of items.

When I had to pin this (discard any number of items above some threshold), I used:

 myList.RemoveRange(threshold, myList.Count - threshold);

      

where threshold is the maximum number of things the list can contain

I have now updated the datatype to Dictionary<key, myClass> myDictionary

How can I basically do the same: Discard all records above a certain threshold. (It doesn't matter which ones get discarded)

My guess is that I could walk through the collection of keys and manually delete all key / value pairs. But I was hoping there was a more elegant solution.

+2


a source to share


1 answer


This code will trim Dictionary

with the name dict

to the maximum size specified maxSize

.



foreach (var obj in dict.Keys.Skip(maxSize).ToList()) dict.Remove(obj);

      

+3


a source







All Articles