System.Linq.Enumerable.ToHashSet<TSource> Method

Namespace: System.Linq
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

Returns

A HashSet<TSource> that contains elements from the input sequence.

Exceptions

Remarks

If the source sequence contains duplicate values, the resulting HashSet<TSource> will contain only one instance of each value.

This method uses deferred execution. When this method is called, it doesn't immediately return a HashSet<TSource>. It stores the enumerable data as a single object to the type that enables it to perform the set operation. The query that obtains the values is not executed until the object is enumerated, either by calling this method or by using a method that enumerates it, such as Count() or ToArray().

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(); // uniqueNumbers will contain: { 1, 2, 3, 4, 5 } foreach (var num in uniqueNumbers) { Console.WriteLine(num); } } }
.NET Core 2.0, .NET Framework 4.6.2, .NET Standard 2.0