Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
17 changes: 17 additions & 0 deletions PowerKit.Tests/CollectionExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using FluentAssertions;
using PowerKit.Extensions;
Expand All @@ -20,4 +22,19 @@ public void RemoveAll_Test()
removed.Should().Be(2);
collection.Should().Equal(1, 3, 5);
}

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

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

// Assert
result.Should().BeOfType<Dictionary<string, int>>();
result.Comparer.Should().Be(StringComparer.Ordinal);
result.Should().Contain("one", 1).And.Contain("two", 2);
Comment thread
Tyrrrz marked this conversation as resolved.
Outdated
}
}
13 changes: 13 additions & 0 deletions PowerKit/Extensions/CollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
Expand Down Expand Up @@ -31,4 +32,16 @@ public int RemoveAll(Func<T, bool> predicate)
return removedCount;
}
}

extension(IDictionary dictionary)
Comment thread
Tyrrrz marked this conversation as resolved.
Outdated
{
/// <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)
Comment thread
Tyrrrz marked this conversation as resolved.
Outdated
where TKey : notnull =>
dictionary
.Cast<DictionaryEntry>()
.ToDictionary(entry => (TKey)entry.Key, entry => (TValue)entry.Value!, comparer);
}
}