Last active
October 16, 2017 18:46
-
-
Save GeorgeTsiokos/b6da22050a0d56e146acc28be8637aa8 to your computer and use it in GitHub Desktop.
CopyTo - KeyValuePair / dictionary extensions
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
public static class KeyValuePairExtensions | |
{ | |
public static void CopyTo<TKey>(this IEnumerable<KeyValuePair<TKey, string>> keyValuePairs, IDictionary<TKey, string> target) => CopyTo(keyValuePairs, target, (a, b) => $"{a},{b}"); | |
public static void CopyTo<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs, IDictionary<TKey, TValue> target, Func<TValue, TValue, TValue> aggregator) | |
{ | |
foreach (var keyValuePair in keyValuePairs) | |
{ | |
var key = keyValuePair.Key; | |
if (target.TryGetValue(key, out var existing)) | |
target[key] = aggregator(existing, keyValuePair.Value); | |
else | |
target[key] = keyValuePair.Value; | |
} | |
} | |
public static void CopyTo<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs, IDictionary<TKey, TValue> target, bool overwrite) | |
{ | |
if (overwrite) | |
CopyOver(keyValuePairs, target); | |
else | |
CopyIfNotExists(keyValuePairs, target); | |
} | |
static void CopyOver<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs, IDictionary<TKey, TValue> target) | |
{ | |
foreach (var keyValuePair in keyValuePairs) | |
target[keyValuePair.Key] = keyValuePair.Value; | |
} | |
static void CopyIfNotExists<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs, IDictionary<TKey, TValue> target) | |
{ | |
foreach (var keyValuePair in keyValuePairs) | |
{ | |
if (target.ContainsKey(keyValuePair.Key)) | |
continue; | |
target[keyValuePair.Key] = keyValuePair.Value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment