Skip to content

Instantly share code, notes, and snippets.

@mizuneko
Created November 10, 2018 03:46
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 mizuneko/78fcb0aa2dd33e10ec6fb5eb086432df to your computer and use it in GitHub Desktop.
Save mizuneko/78fcb0aa2dd33e10ec6fb5eb086432df to your computer and use it in GitHub Desktop.
[Dictionaryのマージ]重複していたらどちらを採用するのか引数で渡してマージ
static public IDictionary<TKey, TValue> Marge<TKey, TValue>(
this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second,
Func<TKey, TValue, TValue, TValue> valueSelector = null)
{
if (valueSelector == null) valueSelector = (key, firVal, secVal) => firVal; //判定条件を省略するとfirst優先
return first.Concat(second)
.GroupBy(pair => pair.Key,
(key, pairs) =>
pairs.Count == 1 ? pairs.First() //重複なし
: new KeyValuePair<TKey, TValue>(key, valueSelector(key, pairs.First().Value, pairs.Last().Value))
).ToDictionary(pair => pair.Key, pair => pair.Value);
}
// Usage:
// dict1とdict2をマージする(キー重複したらdict1を選択)
// var merged = dict1.Merge(dict2);
// キーが重複した際に2つの平均をセットする
// var merged = dict1.Merge(dict2, (key, val1, val2) => (val1 + val2) / 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment