Created
March 25, 2019 20:55
-
-
Save felipeslongo/cb714936317c4174ab3a5aa3d0437e55 to your computer and use it in GitHub Desktop.
Filtering out values from a C# Generic Dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
namespace System.Linq | |
{ | |
/// <summary> | |
/// Filtering out values from a C# Generic Dictionary | |
/// </summary> | |
/// <seealso cref="https://stackoverflow.com/questions/2131648/filtering-out-values-from-a-c-sharp-generic-dictionary"/> | |
public static class IDictionary_WhereToDictionary | |
{ | |
/// <summary> | |
/// If you don't care about creating a new dictionary with the desired items and throwing away the old one, simply try: | |
/// </summary> | |
/// <param name="this"></param> | |
/// <param name="predicate"></param> | |
/// <typeparam name="TKey"></typeparam> | |
/// <typeparam name="TValue"></typeparam> | |
/// <returns></returns> | |
public static Dictionary<TKey, TValue> WhereToDictionary<TKey, TValue>( | |
this IDictionary<TKey, TValue> @this, | |
Func<KeyValuePair<TKey, TValue>, bool> predicate) | |
=> @this.Where(predicate).ToDictionary( | |
kvp => kvp.Key, | |
kvp => kvp.Value); | |
/// <summary> | |
/// 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: | |
/// </summary> | |
/// <param name="this"></param> | |
/// <param name="predicate"></param> | |
/// <typeparam name="TKey"></typeparam> | |
/// <typeparam name="TValue"></typeparam> | |
public static void WhereMutable<TKey, TValue>( | |
this IDictionary<TKey, TValue> @this, | |
Func<KeyValuePair<TKey, TValue>, bool> predicate) | |
{ | |
foreach (var item in @this.Where(predicate).ToList()) | |
@this.Remove(item.Key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment