Created
November 10, 2018 03:46
-
-
Save mizuneko/78fcb0aa2dd33e10ec6fb5eb086432df to your computer and use it in GitHub Desktop.
[Dictionaryのマージ]重複していたらどちらを採用するのか引数で渡してマージ
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
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