From 282d8e4d0e260f7d1a9e3f44c5fa2baae80756e5 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Thu, 22 Feb 2018 16:56:10 -0500 Subject: [PATCH] Dictionary.Update extension method returns a bool for change state --- .../Extensions/DictionaryExtensionsTest.cs | 3 +- .../Extensions/DictionaryExtensions.cs | 35 ++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/ICD.Common.Utils.Tests/Extensions/DictionaryExtensionsTest.cs b/ICD.Common.Utils.Tests/Extensions/DictionaryExtensionsTest.cs index f1c35ab..a6dc00f 100644 --- a/ICD.Common.Utils.Tests/Extensions/DictionaryExtensionsTest.cs +++ b/ICD.Common.Utils.Tests/Extensions/DictionaryExtensionsTest.cs @@ -168,7 +168,8 @@ namespace ICD.Common.Utils.Tests.Extensions {3, 30} }; - a.Update(b); + Assert.IsTrue(a.Update(b)); + Assert.IsFalse(a.Update(b)); Assert.AreEqual(3, a.Count); Assert.AreEqual(10, a[1]); diff --git a/ICD.Common.Utils/Extensions/DictionaryExtensions.cs b/ICD.Common.Utils/Extensions/DictionaryExtensions.cs index 1e5766b..5b79d2d 100644 --- a/ICD.Common.Utils/Extensions/DictionaryExtensions.cs +++ b/ICD.Common.Utils/Extensions/DictionaryExtensions.cs @@ -191,8 +191,9 @@ namespace ICD.Common.Utils.Extensions /// /// /// + /// [PublicAPI] - public static void Update(this IDictionary extends, IDictionary other) + public static bool Update(this IDictionary extends, IDictionary other) { if (extends == null) throw new ArgumentNullException("extends"); @@ -200,8 +201,40 @@ namespace ICD.Common.Utils.Extensions if (other == null) throw new ArgumentNullException("other"); + return extends.Update(other, EqualityComparer.Default); + } + + /// + /// Updates the dictionary with items from the other dictionary. + /// + /// + /// + /// + /// + /// + /// + [PublicAPI] + public static bool Update(this IDictionary extends, IDictionary other, + IEqualityComparer comparer) + { + if (extends == null) + throw new ArgumentNullException("extends"); + + if (other == null) + throw new ArgumentNullException("other"); + + bool change = false; + foreach (KeyValuePair pair in other) + { + if (extends.ContainsKey(pair.Key) && comparer.Equals(pair.Value, extends[pair.Key])) + continue; + extends[pair.Key] = pair.Value; + change = true; + } + + return change; } ///