Set Operations

Set Operations

 

Set operations in LINQ refer to query operations that produce a result set that is based on the presence or absence of equivalent elements within the same or separate collections (or sets).

The standard query operator methods that perform set operations are listed in the following section.

Method Name

Description

C# Query Expression Syntax

Visual Basic Query Expression Syntax

More Information

Distinct

Removes duplicate values from a collection.

Not applicable.

Distinct

Enumerable.Distinct<TSource>

Queryable.Distinct<TSource>

Except

Returns the set difference, which means the elements of one collection that do not appear in a second collection.

Not applicable.

Not applicable.

Enumerable.Except<TSource>

Queryable.Except<TSource>

Intersect

Returns the set intersection, which means elements that appear in each of two collections.

Not applicable.

Not applicable.

Enumerable.Intersect<TSource>

Queryable.Intersect<TSource>

Union

Returns the set union, which means unique elements that appear in either of two collections.

Not applicable.

Not applicable.

Enumerable.Union<TSource>

Queryable.Union<TSource>

The following illustration depicts the behavior of the Enumerable.Distinct<TSource> method on a sequence of characters. The returned sequence contains the unique elements from the input sequence.

Graphic showing the behavior of Distinct().

The following illustration depicts the behavior of Enumerable.Except<TSource>. The returned sequence contains only the elements from the first input sequence that are not in the second input sequence.

Graphic showing the action of Except().

The following illustration depicts the behavior of Enumerable.Intersect<TSource>. The returned sequence contains the elements that are common to both of the input sequences.

Graphic showing the intersection of two sequences.

The following illustration depicts a union operation on two sequences of characters. The returned sequence contains the unique elements from both input sequences.

Graphic showing the union of two sequences.

The following example uses the Distinct clause (available in Visual Basic only) in a LINQ query to return the unique numbers from a list of integers.


Dim classGrades = New System.Collections.Generic.List(Of Integer) From {63, 68, 71, 75, 68, 92, 75}

Dim distinctQuery = From grade In classGrades 
                    Select grade Distinct

Dim sb As New System.Text.StringBuilder("The distinct grades are: ")
For Each number As Integer In distinctQuery
    sb.Append(number & " ")
Next

' Display the results.
MsgBox(sb.ToString())

' This code produces the following output:

' The distinct grades are: 63 68 71 75 92 

Show:
© 2016 Microsoft