| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- using System;
- using System.Collections.Generic;
- namespace FF8
- {
- /// <summary>
- /// class to add function to dictionary
- /// </summary>
- /// <see cref="https://stackoverflow.com/questions/22595655/how-to-do-a-dictionary-reverse-lookup"/>
- /// <seealso cref="https://stackoverflow.com/questions/6050633/why-doesnt-dictionary-have-addrange"/>
- public static class DictionaryEx
- {
- #region Methods
- /// <summary>
- /// Reverses Key and Value of dictionary.
- /// </summary>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- /// <param name="source"></param>
- /// <returns></returns>
- public static Dictionary<TValue, TKey> Reverse<TKey, TValue>(this IDictionary<TKey, TValue> source)
- {
- Dictionary<TValue, TKey> dictionary = new Dictionary<TValue, TKey>();
- foreach (KeyValuePair<TKey, TValue> entry in source)
- {
- if (!dictionary.ContainsKey(entry.Value))
- dictionary.Add(entry.Value, entry.Key);
- }
- return dictionary;
- }
- public static void AddRangeOverride<TKey, TValue>(this Dictionary<TKey, TValue> dic, Dictionary<TKey, TValue> dicToAdd)
- {
- dicToAdd.ForEach(x => dic[x.Key] = x.Value);
- }
- public static void AddRangeNewOnly<TKey, TValue>(this Dictionary<TKey, TValue> dic, Dictionary<TKey, TValue> dicToAdd)
- {
- dicToAdd.ForEach(x => { if (!dic.ContainsKey(x.Key)) dic.Add(x.Key, x.Value); });
- }
- public static void AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dic, Dictionary<TKey, TValue> dicToAdd)
- {
- dicToAdd.ForEach(x => dic.Add(x.Key, x.Value));
- }
- public static bool ContainsKeys<TKey, TValue>(this Dictionary<TKey, TValue> dic, IEnumerable<TKey> keys)
- {
- bool result = false;
- keys.ForEachOrBreak((x) => { result = dic.ContainsKey(x); return result; });
- return result;
- }
- public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
- {
- foreach (var item in source)
- action(item);
- }
- public static void ForEachOrBreak<T>(this IEnumerable<T> source, Func<T, bool> func)
- {
- foreach (var item in source)
- {
- bool result = func(item);
- if (result) break;
- }
- }
- #endregion Methods
- }
- }
|