diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d34d70..314dc24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - New XML conversion framework for performance improvements ### Changed - XmlUtils is now using the improved XML conversion framework + - Better implementation of DictionaryExtensions.ToInverse ## [5.0.0] - 2018-09-14 ### Added diff --git a/ICD.Common.Utils.Tests/Extensions/DictionaryExtensionsTest.cs b/ICD.Common.Utils.Tests/Extensions/DictionaryExtensionsTest.cs index 365cc1c..469bbb5 100644 --- a/ICD.Common.Utils.Tests/Extensions/DictionaryExtensionsTest.cs +++ b/ICD.Common.Utils.Tests/Extensions/DictionaryExtensionsTest.cs @@ -301,5 +301,29 @@ namespace ICD.Common.Utils.Tests.Extensions Assert.AreEqual(20, ordered[1]); Assert.AreEqual(30, ordered[2]); } + + [Test] + public void ToInverseTest() + { + Dictionary forward = new Dictionary + { + { 1, "testA" }, + { 2, "testA" }, + { 3, "testB" }, + { 4, "testB" } + }; + + Dictionary> backwards = new Dictionary> + { + {"testA", new List {1, 2}}, + {"testB", new List {3, 4}} + }; + + Dictionary> inverse = forward.ToInverse(); + + bool equal = inverse.DictionaryEqual(backwards, (v1, v2) => v1.ScrambledEquals(v2)); + + Assert.IsTrue(equal); + } } } diff --git a/ICD.Common.Utils/Extensions/DictionaryExtensions.cs b/ICD.Common.Utils/Extensions/DictionaryExtensions.cs index 7ffc580..a77ec99 100644 --- a/ICD.Common.Utils/Extensions/DictionaryExtensions.cs +++ b/ICD.Common.Utils/Extensions/DictionaryExtensions.cs @@ -452,12 +452,26 @@ namespace ICD.Common.Utils.Extensions /// /// [PublicAPI] - public static Dictionary ToInverse(this IEnumerable> extends) + public static Dictionary> ToInverse(this IEnumerable> extends) { if (extends == null) throw new ArgumentNullException("extends"); - return extends.ToDictionary(kvp => kvp.Value, kvp => kvp.Key); + Dictionary> output = new Dictionary>(); + + foreach (KeyValuePair kvp in extends) + { + List keys; + if (!output.TryGetValue(kvp.Value, out keys)) + { + keys = new List(); + output.Add(kvp.Value, keys); + } + + keys.Add(kvp.Key); + } + + return output; } } }