Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
39 changes: 39 additions & 0 deletions PowerKit.Tests/DictionaryExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;
using System.Collections;
using System.Collections.Generic;
using FluentAssertions;
using PowerKit.Extensions;
using Xunit;

namespace PowerKit.Tests;

public class DictionaryExtensionsTests
{
[Fact]
public void ToDictionary_Test()
{
// Arrange
var source = (IDictionary)new Hashtable { ["one"] = 1, ["two"] = 2 };

// Act
var result = source.ToDictionary<string, int>();

// Assert
result.Should().BeOfType<Dictionary<string, int>>();
result.Should().Contain("one", 1).And.Contain("two", 2);
}

[Fact]
public void ToDictionary_CustomComparer_Test()
{
// Arrange
var source = (IDictionary)new Hashtable { ["one"] = 1, ["two"] = 2 };

// Act
var result = source.ToDictionary<string, int>(StringComparer.OrdinalIgnoreCase);

// Assert
result.Should().BeOfType<Dictionary<string, int>>();
result.Should().Contain("ONE", 1).And.Contain("TWO", 2);
}
}
32 changes: 32 additions & 0 deletions PowerKit/Extensions/DictionaryExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#nullable enable
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace PowerKit.Extensions;

#if !POWERKIT_INCLUDE_COVERAGE
[ExcludeFromCodeCoverage]
#endif
internal static class DictionaryExtensions
{
extension(IDictionary dictionary)
{
/// <summary>
/// Converts a non-generic dictionary to a typed <see cref="Dictionary{TKey, TValue}"/> using the specified comparer.
/// </summary>
public Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(IEqualityComparer<TKey> comparer)
where TKey : notnull =>
dictionary
.Cast<DictionaryEntry>()
.ToDictionary(entry => (TKey)entry.Key, entry => (TValue)entry.Value!, comparer);

/// <summary>
/// Converts a non-generic dictionary to a typed <see cref="Dictionary{TKey, TValue}"/> using the default comparer.
/// </summary>
public Dictionary<TKey, TValue> ToDictionary<TKey, TValue>()
where TKey : notnull =>
dictionary.ToDictionary<TKey, TValue>(EqualityComparer<TKey>.Default);
}
}