Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active June 22, 2020 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/5dd1b707bfcba3480b8e3749c8e8319e to your computer and use it in GitHub Desktop.
Save gsscoder/5dd1b707bfcba3480b8e3749c8e8319e to your computer and use it in GitHub Desktop.
Simple C# pure extension methods for dictionaries
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