System.Linq.Enumerable.ToHashSet<TSource> Method
Creates a HashSet<TSource>
from an IEnumerable<TSource>
by using the default equality comparer for the element type.
Syntax
public static HashSet<TSource> ToHashSet<TSource>(this IEnumerable<TSource> source)
Parameters
-
source:
An
IEnumerable<TSource>
to create a HashSet<TSource>
from.
Returns
A HashSet<TSource>
that contains elements from the input sequence.
Exceptions
-
TSource:
The type of the elements in the sequence.
-
ArgumentNullException:
source
is null.
Remarks
Examples
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 4, 5 };
HashSet<int> uniqueNumbers = numbers.ToHashSet();
foreach (var num in uniqueNumbers)
{
Console.WriteLine(num);
}
}
}
.NET Core 2.0, .NET Framework 4.6.2, .NET Standard 2.0