Filtering out values from a C# Generic Dictionary

后端 未结 6 1974
难免孤独
难免孤独 2020-12-02 16:29

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

For example, I want to

6条回答
  •  Happy的楠姐
    2020-12-02 16:50

    I added the following extension method for my project which allows you to filter an IDictionary.

    public static IDictionary KeepWhen(
        this IDictionary dict,
        Predicate predicate
    ) {
        return dict.Aggregate(
            new Dictionary(),
            (result, keyValPair) =>
            {
                var key = keyValPair.Key;
                var val = keyValPair.Value;
    
                if (predicate(val))
                    result.Add(key, val);
    
                return result;
            }
        );
    }
    

    Usage:

    IDictionary oldPeople = personIdToPerson.KeepWhen(p => p.age > 29);
    

提交回复
热议问题