Skip to content

Commit f18dcfe

Browse files
authored
add IEnumerable<T>.ToHashSet (#125)
1 parent ebf9c0c commit f18dcfe

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/Polyfill/Polyfill_IEnumerable.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,4 +286,21 @@ public static IEnumerable<TSource> SkipLast<TSource>(
286286
int count) =>
287287
target.Reverse().Skip(count).Reverse();
288288
#endif
289+
290+
#if NET471 || NET46X || NETSTANDARD2_0
291+
292+
/// <summary>
293+
/// Creates a HashSet<T> from an IEnumerable<T> using the comparer to compare keys.
294+
/// </summary>
295+
/// <param name="source">An IEnumerable<T> to create a HashSet<T> from.</param>
296+
/// <param name="comparer">An IEqualityComparer<T> to compare keys.</param>
297+
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
298+
/// <returns>A HashSet<T> that contains values of type TSource selected from the input sequence.</returns>
299+
[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)))")]
300+
public static HashSet<TSource> ToHashSet<TSource>(
301+
this IEnumerable<TSource> target,
302+
IEqualityComparer<TSource>? comparer = null) =>
303+
new HashSet<TSource>(target, comparer);
304+
305+
#endif
289306
}

src/Tests/PolyfillTests_IEnumerable.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,16 @@ public void IEnumerableSkipLast()
3939
Assert.IsTrue(enumerable.SkipLast(1).SequenceEqual(new List<string> { "a" }));
4040
}
4141

42+
[Test]
43+
public void ToHashSet ()
44+
{
45+
var enumerable = (IEnumerable<string>)new List<string> { "a", "b" };
46+
47+
var hashSet = enumerable.ToHashSet();
48+
Assert.IsTrue(hashSet.Contains("a"));
49+
Assert.IsTrue(hashSet.Contains("b"));
50+
}
51+
4252
[Test]
4353
public void Chunk_SizeOf3()
4454
{

0 commit comments

Comments
 (0)