Partager via


Invert Dictionary

 using System.Collections.Generic;
using System.Linq;

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static Dictionary<V, K[]> Invert<K, V>(this Dictionary<K, V[]> dict)
        {
            var x = new Dictionary<V, IList<K>>();
            foreach (var kvp in dict)
            {
                if (kvp.Value != null)
                {
                    foreach (var value in kvp.Value)
                    {
                        IList<K> list;
                        if (!x.TryGetValue(value, out list))
                        {
                            x[value] = list = new List<K>();
                        }
                        if (!list.Contains(kvp.Key))
                        {
                            list.Add(kvp.Key);
                        }
                    }
                }
            }
            var answer = new Dictionary<V, K[]>();
            foreach (var kvp in x)
            {
                answer[kvp.Key] = kvp.Value.ToArray();
            }
            return answer;
        }
    }
}
 
 static void TestInvertDictionary(string[] args)
        {
            Dictionary<string, string[]> dict = new Dictionary<string, string[]>();
            dict["0"] = new string[] { "a", "b", "c" };
            dict["1"] = new string[] { "b", "c", "d" };
            dict["2"] = null;
            dict["3"] = new string[] { "x", "y", "z" };
            dict["4"] = new string[] { "s", "i", "d" };
            dict["5"] = new string[] { "p", "o", "o", "j", "a" };            
            foreach (var kvp in dict.Invert())
            {
                Console.Write(kvp.Key + " : ");
                foreach (var item in kvp.Value)
                {
                    Console.Write(item + " , ");
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }