diff --git a/PowerKit.Tests/Extensions/DictionaryExtensionsTests.cs b/PowerKit.Tests/Extensions/DictionaryExtensionsTests.cs index 7fa81ac..94d5b5a 100644 --- a/PowerKit.Tests/Extensions/DictionaryExtensionsTests.cs +++ b/PowerKit.Tests/Extensions/DictionaryExtensionsTests.cs @@ -9,6 +9,17 @@ namespace PowerKit.Tests.Extensions; public class DictionaryExtensionsTests { + [Fact] + public void GetValueOrNull_Test() + { + // Arrange + var source = (IDictionary)new Dictionary { ["one"] = 1 }; + + // Act & assert + source.GetValueOrNull("one").Should().Be(1); + source.GetValueOrNull("two").Should().BeNull(); + } + [Fact] public void ToDictionary_Test() { diff --git a/PowerKit.Tests/Extensions/ReadOnlyDictionaryExtensionsTests.cs b/PowerKit.Tests/Extensions/ReadOnlyDictionaryExtensionsTests.cs new file mode 100644 index 0000000..c4b00a4 --- /dev/null +++ b/PowerKit.Tests/Extensions/ReadOnlyDictionaryExtensionsTests.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using FluentAssertions; +using PowerKit.Extensions; +using Xunit; + +namespace PowerKit.Tests.Extensions; + +public class ReadOnlyDictionaryExtensionsTests +{ + [Fact] + public void GetValueOrNull_Test() + { + // Arrange + var source = (IReadOnlyDictionary)new Dictionary { ["one"] = 1 }; + + // Act & assert + source.GetValueOrNull("one").Should().Be(1); + source.GetValueOrNull("two").Should().BeNull(); + } +} diff --git a/PowerKit/Extensions/DictionaryExtensions.cs b/PowerKit/Extensions/DictionaryExtensions.cs index 9cd9a13..8555069 100644 --- a/PowerKit/Extensions/DictionaryExtensions.cs +++ b/PowerKit/Extensions/DictionaryExtensions.cs @@ -11,6 +11,17 @@ namespace PowerKit.Extensions; #endif internal static class DictionaryExtensions { + extension(IDictionary dictionary) + where TKey : notnull + where TValue : struct + { + /// + /// Returns the value associated with the specified key, or if the key is not found. + /// + public TValue? GetValueOrNull(TKey key) => + dictionary.TryGetValue(key, out var value) ? value : null; + } + extension(IDictionary dictionary) { /// diff --git a/PowerKit/Extensions/ReadOnlyDictionaryExtensions.cs b/PowerKit/Extensions/ReadOnlyDictionaryExtensions.cs new file mode 100644 index 0000000..d682c77 --- /dev/null +++ b/PowerKit/Extensions/ReadOnlyDictionaryExtensions.cs @@ -0,0 +1,24 @@ +#if NET40_OR_GREATER || NETSTANDARD || NET +#nullable enable +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace PowerKit.Extensions; + +#if !POWERKIT_INCLUDE_COVERAGE +[ExcludeFromCodeCoverage] +#endif +internal static class ReadOnlyDictionaryExtensions +{ + extension(IReadOnlyDictionary dictionary) + where TKey : notnull + where TValue : struct + { + /// + /// Returns the value associated with the specified key, or if the key is not found. + /// + public TValue? GetValueOrNull(TKey key) => + dictionary.TryGetValue(key, out var value) ? value : null; + } +} +#endif