Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering out values from a C# Generic Dictionary

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?

like image 896
Fiona - myaccessible.website Avatar asked Jan 25 '10 10:01

Fiona - myaccessible.website


People also ask

What is filtering C?

A "filter" program is simply a program which reads from the standard input stream ( stdin ) and writes to the standard output stream ( stdout ).

How do you filter a list in C#?

In the first example, we use a foreach loop to filter a list. var words = new List<string> { "sky", "rock", "forest", "new", "falcon", "jewelry" }; var filtered = new List<string>(); foreach (var word in words) { if (word. Length == 3) { filtered. Add(word); } } Console.


2 Answers

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.

like image 50
mmx Avatar answered Sep 23 '22 10:09

mmx


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

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

To recreate a new dictionary if you need it, use the ToDictionary method.

like image 35
Lee Avatar answered Sep 23 '22 10:09

Lee