Filtering out values from a C# Generic Dictionary

后端 未结 6 1986
难免孤独
难免孤独 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:06

    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.

提交回复
热议问题