From bca2d29087d59ad9d6d4e367266b7ceb30fc083f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sat, 13 Jan 2024 21:11:19 +1100 Subject: [PATCH] add IEnumerable.ToHashSet --- src/Polyfill/Polyfill_IEnumerable.cs | 17 +++++++++++++++++ src/Tests/PolyfillTests_IEnumerable.cs | 10 ++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/Polyfill/Polyfill_IEnumerable.cs b/src/Polyfill/Polyfill_IEnumerable.cs index d433f9b1..f5e211ac 100644 --- a/src/Polyfill/Polyfill_IEnumerable.cs +++ b/src/Polyfill/Polyfill_IEnumerable.cs @@ -286,4 +286,21 @@ public static IEnumerable SkipLast( int count) => target.Reverse().Skip(count).Reverse(); #endif + +#if NET471 || NET46X || NETSTANDARD2_0 + + /// + /// Creates a HashSet from an IEnumerable using the comparer to compare keys. + /// + /// An IEnumerable to create a HashSet from. + /// An IEqualityComparer to compare keys. + /// The type of the elements of source. + /// A HashSet that contains values of type TSource selected from the input sequence. + [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 ToHashSet( + this IEnumerable target, + IEqualityComparer? comparer = null) => + new HashSet(target, comparer); + +#endif } \ No newline at end of file diff --git a/src/Tests/PolyfillTests_IEnumerable.cs b/src/Tests/PolyfillTests_IEnumerable.cs index cbeb15ec..c230ec31 100644 --- a/src/Tests/PolyfillTests_IEnumerable.cs +++ b/src/Tests/PolyfillTests_IEnumerable.cs @@ -39,6 +39,16 @@ public void IEnumerableSkipLast() Assert.IsTrue(enumerable.SkipLast(1).SequenceEqual(new List { "a" })); } + [Test] + public void ToHashSet () + { + var enumerable = (IEnumerable)new List { "a", "b" }; + + var hashSet = enumerable.ToHashSet(); + Assert.IsTrue(hashSet.Contains("a")); + Assert.IsTrue(hashSet.Contains("b")); + } + [Test] public void Chunk_SizeOf3() {