Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions PowerKit.Tests/Extensions/DictionaryExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,58 @@ namespace PowerKit.Tests.Extensions;

public class DictionaryExtensionsTests
{
[Fact]
public void GetValueOrNull_Found_Test()
Comment thread
Tyrrrz marked this conversation as resolved.
Resolved
{
// Arrange
IDictionary<string, int> source = new Dictionary<string, int> { ["one"] = 1 };
Comment thread
Tyrrrz marked this conversation as resolved.
Resolved

// Act
var result = source.GetValueOrNull("one");

// Assert
result.Should().Be(1);
}

[Fact]
public void GetValueOrNull_NotFound_Test()
{
// Arrange
IDictionary<string, int> source = new Dictionary<string, int> { ["one"] = 1 };

// Act
var result = source.GetValueOrNull("two");

// Assert
result.Should().BeNull();
}

[Fact]
public void GetValueOrNull_ReadOnly_Found_Test()
{
// Arrange
IReadOnlyDictionary<string, int> source = new Dictionary<string, int> { ["one"] = 1 };

// Act
var result = source.GetValueOrNull("one");

// Assert
result.Should().Be(1);
}

[Fact]
public void GetValueOrNull_ReadOnly_NotFound_Test()
{
// Arrange
IReadOnlyDictionary<string, int> source = new Dictionary<string, int> { ["one"] = 1 };

// Act
var result = source.GetValueOrNull("two");

// Assert
result.Should().BeNull();
}

[Fact]
public void ToDictionary_Test()
{
Expand Down
24 changes: 24 additions & 0 deletions PowerKit/Extensions/DictionaryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,30 @@ namespace PowerKit.Extensions;
#endif
internal static class DictionaryExtensions
{
extension<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
where TKey : notnull
where TValue : struct
{
/// <summary>
/// Returns the value associated with the specified key, or <see langword="null" /> if the key is not found.
/// </summary>
public TValue? GetValueOrNull(TKey key) =>
dictionary.TryGetValue(key, out var value) ? value : null;
}

#if NET40_OR_GREATER || NETSTANDARD || NET
extension<TKey, TValue>(IReadOnlyDictionary<TKey, TValue> dictionary)
Comment thread
Tyrrrz marked this conversation as resolved.
Resolved
where TKey : notnull
where TValue : struct
{
/// <summary>
/// Returns the value associated with the specified key, or <see langword="null" /> if the key is not found.
/// </summary>
public TValue? GetValueOrNull(TKey key) =>
dictionary.TryGetValue(key, out var value) ? value : null;
}
#endif

extension(IDictionary dictionary)
{
/// <summary>
Expand Down