Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static Dictionary<TKey,TValue>
- Merge<TKey,TValue>(Dictionary<TKey,TValue>[] dictionaries);
- public static Dictionary<TKey,TValue>
- Merge<TKey,TValue>(IEnumerable<Dictionary<TKey,TValue>> dictionaries);
- var result = dictionaries.SelectMany(dict => dict)
- .ToDictionary(pair => pair.Key, pair => pair.Value);
- var result = dictionaries.SelectMany(dict => dict)
- .ToLookup(pair => pair.Key, pair => pair.Value)
- .ToDictionary(group => group.Key, group => group.First());
- public static class DictionaryExtensions
- {
- // Works in C#3/VS2080:
- // Returns a new dictionary of this ... others merged leftward.
- // Keeps the type of 'this', which must be default-instantiable.
- // Example:
- // result = map.MergeLeft(other1, other2, ...)
- public static T MergeLeft<T,K,V>(this T me, params IDictionary<K,V>[] others)
- where T : IDictionary<K,V>, new()
- {
- T newMap = new T();
- foreach (IDictionary<K,V> src in
- (new List<IDictionary<K,V>> { me }).Concat(others)) {
- // ^-- echk. Not quite there type-system.
- foreach (KeyValuePair<K,V> p in src) {
- newMap[p.Key] = p.Value;
- }
- }
- return newMap;
- }
- }
- using System.Collections.Generic;
- ...
- public static Dictionary<TKey, TValue>
- Merge<TKey,TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)
- {
- var result = new Dictionary<TKey, TValue>();
- foreach (var dict in dictionaries)
- foreach (var x in dict)
- result[x.Key] = x.Value;
- return result;
- }
- static Dictionary<TKey, TValue>
- Merge<TKey, TValue>(this IEnumerable<Dictionary<TKey, TValue>> enumerable)
- {
- return enumerable.SelectMany(x => x).ToDictionary(x => x.Key, y => y.Value);
- }
- Dictionary<String, String> allTables = new Dictionary<String, String>();
- allTables = tables1.Union(tables2).ToDictionary(pair => pair.Key, pair => pair.Value);
- public static IDictionary<TKey, TValue> Merge<TKey, TValue>(IEnumerable<IDictionary<TKey, TValue>> dictionaries)
- {
- // ...
- }
- public static IDictionary<TKey, TValue> Merge<TKey, TValue>(params IDictionary<TKey, TValue>[] dictionaries)
- {
- return Merge((IEnumerable<TKey, TValue>) dictionaries);
- }
- using System.Collections.Generic;
- namespace HelperMethods
- {
- public static class MergeDictionaries
- {
- public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
- {
- if (second == null) return;
- if (first == null) first = new Dictionary<TKey, TValue>();
- foreach (var item in second)
- if (!first.ContainsKey(item.Key))
- first.Add(item.Key, item.Value);
- }
- }
- }
- dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));
Add Comment
Please, Sign In to add comment