views:

48

answers:

1

I had a List<myClass> myList for storing a list of items.

When I had to clip this (discard any amount of items above some threshold) I used:

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

where threshold is the max amount of things the list can contain

Now I've upgraded the datatype to a Dictionary<key, myClass> myDictionary

How can I basically do the same: Discard all entries above some threshold. (It doesn't matter which ones are discarded)

I guess I could foreach through the keys collection and manually delete all keys/value pairs. But I was hoping there was a more elegant solution.

+3  A: 

This code will trim a Dictionary named dict to the maximum size specified by maxSize.

foreach (var obj in dict.Keys.Skip(maxSize).ToList()) dict.Remove(obj);
Adam Robinson
+1 Elegant solution! You could pack this into a extension method like: `public static void Trim<TKey, TValue>(this IDictionary<TKey, TValue> dict, int max) { foreach (TKey key in dict.Keys.Skip(max).ToList()) dict.Remove(key); }`
Philip Daubmeier