mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-01-11 19:44:55 +00:00
feat: Better implementation of DictionaryExtensions.ToInverse
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user