I have a C# dictionary, Dictionary
that I need to be filtered based on a property of MyObject
.
For example, I want to
Here is a general solution, working not only for boolean properties of the values.
Method
Reminder: Extension methods must be placed in static classes. Dont forget the using System.Linq;
statement at the top of the source file.
///
/// Creates a filtered copy of this dictionary, using the given predicate.
///
public static Dictionary Filter(this Dictionary dict,
Predicate> pred) {
return dict.Where(it => pred(it)).ToDictionary(it => it.Key, it => it.Value);
}
Usage
Example:
var onlyWithPositiveValues = allNumbers.Filter(it => it.Value > 0);