views:

521

answers:

3

I have a C# dictionary, Dictionary<Guid, MyObject> that I need to be filtered based on a property of MyObject.

For example, I want to remove all records from the dictionary where MyObject.BooleanProperty = false. What is the best way of acheiving this?

+10  A: 

Since Dictionary implements IEnumerable<KeyValuePair<Key, Value>>, you can just use where:

var matches = dictionary.Where(kvp => !kvp.Value.BooleanProperty);

To can recreate a new dictionary if you need it using ToDictionary

Lee
LINQ makes life so easy! :)
SirDemon
+7  A: 

If you don't care about creating a new dictionary with the desired items and throwing away the old one, simply try:

dic = dic.Where(i => i.Value.BooleanProperty)
         .ToDictionary(i => i.Key, i => i.Value);

If you can't create a new dictionary and need to alter the old one for some reason (like when it's externally referenced and you can't update all the references:

foreach (var item in dic.Where(item => !item.Value.BooleanProperty).ToList())
    dic.Remove(item.Key);

Note that ToList is necessary here since you're modifying the underlying collection. If you change the underlying collection, the enumerator working on it to query the values will be unusable and will throw an exception in the next loop iteration. ToList caches the values before altering the dictionary at all.

Mehrdad Afshari
+3  A: 

You can simply use the Linq where clause:

var filtered = from kvp in myDictionary
               where !kvp.Value.BooleanProperty
               select kvp
Oded
`select` clause is necessary in the LINQ query expression syntax.
Mehrdad Afshari
@Mehrdad Afshari - Thanks for the correction
Oded