Skip to content

Commit

Permalink
add IEnumerable<T>.ToHashSet (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp authored Jan 13, 2024
1 parent ebf9c0c commit f18dcfe
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Polyfill/Polyfill_IEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,4 +286,21 @@ public static IEnumerable<TSource> SkipLast<TSource>(
int count) =>
target.Reverse().Skip(count).Reverse();
#endif

#if NET471 || NET46X || NETSTANDARD2_0

/// <summary>
/// Creates a HashSet<T> from an IEnumerable<T> using the comparer to compare keys.
/// </summary>
/// <param name="source">An IEnumerable<T> to create a HashSet<T> from.</param>
/// <param name="comparer">An IEqualityComparer<T> to compare keys.</param>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <returns>A HashSet<T> that contains values of type TSource selected from the input sequence.</returns>
[Link("https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tohashset#system-linq-enumerable-tohashset-1(system-collections-generic-ienumerable((-0))-system-collections-generic-iequalitycomparer((-0)))")]
public static HashSet<TSource> ToHashSet<TSource>(
this IEnumerable<TSource> target,
IEqualityComparer<TSource>? comparer = null) =>
new HashSet<TSource>(target, comparer);

#endif
}
10 changes: 10 additions & 0 deletions src/Tests/PolyfillTests_IEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ public void IEnumerableSkipLast()
Assert.IsTrue(enumerable.SkipLast(1).SequenceEqual(new List<string> { "a" }));
}

[Test]
public void ToHashSet ()
{
var enumerable = (IEnumerable<string>)new List<string> { "a", "b" };

var hashSet = enumerable.ToHashSet();
Assert.IsTrue(hashSet.Contains("a"));
Assert.IsTrue(hashSet.Contains("b"));
}

[Test]
public void Chunk_SizeOf3()
{
Expand Down

0 comments on commit f18dcfe

Please sign in to comment.