Last active
June 22, 2020 09:52
-
-
Save gsscoder/5dd1b707bfcba3480b8e3749c8e8319e to your computer and use it in GitHub Desktop.
Simple C# pure extension methods for dictionaries
This file contains 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; | |
public static class DictionaryExtensions | |
{ | |
public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> target, IDictionary<T, U> source) | |
{ | |
var result = new Dictionary<T, U>(target); | |
foreach (var pair in target) { | |
if (source.ContainsKey(pair.Key)) { | |
result[pair.Key] = source[pair.Key]; | |
} | |
} | |
foreach (var pair in source) { | |
if (!target.ContainsKey(pair.Key)) { | |
result[pair.Key] = pair.Value; | |
} | |
} | |
return result; | |
} | |
public static IDictionary<T, U> Insert<T, U>(this IDictionary<T, U> source, T key, U value, bool before = false) | |
{ | |
IDictionary<T, U> result; | |
switch (before) { | |
default: | |
result = new Dictionary<T, U>(); | |
result.Add(key, value); | |
return result.Merge(source); | |
case false: | |
result = new Dictionary<T, U>(source); | |
result.Add(key, value); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment