C# Reference ยท LINQ
LINQ ToHashSet() method
Reference for LINQ ToHashSet() in C#: copy a sequence into a HashSet<T>, remove duplicates, use a custom comparer and get fast Contains() lookups.
ToHashSet() enumerates a sequence once and copies its elements into a new HashSet<T>. Duplicates are dropped silently, and the result answers Contains() in constant time on average. It is the right terminal operation when you want a fast membership test or a de-duplicated collection you can keep changing.
Unlike most LINQ operators it runs immediately (it is a materializing operator), so the set is a snapshot: later changes to the source do not affect it.
HashSet<string> tags = posts.SelectMany(p => p.Tags).ToHashSet(); var ids = users.Select(u => u.Id).ToHashSet();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static HashSet<TSource> ToHashSet<TSource>( this IEnumerable<TSource> source); public static HashSet<TSource> ToHashSet<TSource>( this IEnumerable<TSource> source, IEqualityComparer<TSource>? comparer);
| Name | Description |
|---|---|
source |
The sequence to copy. |
comparer |
Decides which elements are equal. null or omitted uses the default comparer for TSource. |
Returns: a new HashSet<TSource> containing the distinct elements.
Errors: ArgumentNullException if source is null.
Usage notes
- Immediate execution. The source is enumerated exactly once, right at the call. Compare with
Distinct(), which is lazy. - Order is not a feature. A
HashSet<T>makes no promise about enumeration order, so sort (Order(),OrderBy()) before printing or comparing text output. - Equality. Without a comparer, elements are compared with
Equals()andGetHashCode(). Records get value equality for free; plain classes compare by reference unless you override both members. - First one wins. When two elements are equal under the comparer, the first one seen is kept and the later one is ignored.
- Cost. O(n) time on average and O(n) memory. For a one-off check on a tiny list,
Contains()on the original list is cheaper than building a set; for repeated lookups the set wins quickly. - Mutable keys are a trap. If you change a property that takes part in
GetHashCode()after adding an element, the set can no longer find it. - Availability.
ToHashSet()was added in .NET Framework 4.7.2 and .NET Core 2.0. It is not available forIQueryable<T>as a translated operator; it simply pulls the data into memory. - Set algebra. Once you hold a
HashSet<T>, methods such asUnionWith(),IntersectWith()andIsSubsetOf()modify or compare sets in place. SeeUnion(),Intersect(),Except()for the lazy equivalents.