HashSet and LINQ Set Operations

This topic compares HashSet<T> operations and Language-Integrated Query (LINQ) set operations.

LINQ Set Operations

LINQ provides access to some set operations to any data source that implements the IEnumerable or IQueryable interfaces. This includes arrays and collections.

The set operations that LINQ provides are as follows:

  • Distinct

  • Union

  • Intersect

  • Except

For more information about LINQ, see LINQ (Language-Integrated Query) and Parallel LINQ (PLINQ). For more information about LINQ set operations, see Set Operations.

When to Use HashSet<T>

The primary difference between LINQ set operations and HashSet<T> operations is that LINQ set operations always return a new IEnumerable<T> collection, whereas the HashSet<T> equivalent methods modify the current collection. HashSet<T> provides a larger and more robust collection of set operations. For example, HashSet<T> provides comparisons such as IsSubsetOf and IsSupersetOf.

Typically, if you must create a new set or if your application needs access only to the provided set operations, using LINQ set operations on any IEnumerable<T> collection or array will be sufficient. However, if your application requires access to additional set operations, or if it is not desirable or necessary to create a new collection, use the HashSet<T> class.

HashSet<T> and LINQ Set Operations

The following table shows the HashSet<T> operations and their equivalent LINQ set operations.

HashSet(Of T) operation

LINQ equivalent

UnionWith

Union

IntersectWith

Intersect

ExceptWith

Except

Not provided.

Distinct

SymmetricExceptWith

Not provided.

Overlaps

Not provided.

IsSubsetOf

Not provided.

IsProperSubsetOf

Not provided.

IsSupersetOf

Not provided.

IsProperSupersetOf

Not provided.

SetEquals

Not provided.

See Also

Reference

HashSet<T>

Concepts

HashSet Collection Type

Parallel LINQ (PLINQ)

Set Operations

Other Resources

LINQ (Language-Integrated Query)

Commonly Used Collection Types