Filtering out values from a C# Generic Dictionary

后端 未结 6 1967
难免孤独
难免孤独 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 17:08

    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);
    

提交回复
热议问题