feat: Better implementation of DictionaryExtensions.ToInverse

This commit is contained in:
Chris Cameron
2018-10-16 14:31:53 -04:00
parent 23a068d0c9
commit 85ab631ef5
3 changed files with 41 additions and 2 deletions

View File

@@ -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

View File

@@ -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<int, string> forward = new Dictionary<int, string>
{
{ 1, "testA" },
{ 2, "testA" },
{ 3, "testB" },
{ 4, "testB" }
};
Dictionary<string, List<int>> backwards = new Dictionary<string, List<int>>
{
{"testA", new List<int> {1, 2}},
{"testB", new List<int> {3, 4}}
};
Dictionary<string, List<int>> inverse = forward.ToInverse();
bool equal = inverse.DictionaryEqual(backwards, (v1, v2) => v1.ScrambledEquals(v2));
Assert.IsTrue(equal);
}
}
}

View File

@@ -452,12 +452,26 @@ namespace ICD.Common.Utils.Extensions
/// <param name="extends"></param>
/// <returns></returns>
[PublicAPI]
public static Dictionary<TValue, TKey> ToInverse<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> extends)
public static Dictionary<TValue, List<TKey>> ToInverse<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> extends)
{
if (extends == null)
throw new ArgumentNullException("extends");
return extends.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
Dictionary<TValue, List<TKey>> output = new Dictionary<TValue, List<TKey>>();
foreach (KeyValuePair<TKey, TValue> kvp in extends)
{
List<TKey> keys;
if (!output.TryGetValue(kvp.Value, out keys))
{
keys = new List<TKey>();
output.Add(kvp.Value, keys);
}
keys.Add(kvp.Key);
}
return output;
}
}
}