Set operations 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).
Distinct
Removes duplicate values from a collection.
Method Syntax
// Distinct
var numbers = new int[] { 1, 2, 3, 1, 2, 3 };
var distinct = numbers.Distinct();
// distinct = { 1, 2, 3 }
Query Syntax
// Not applicable.
Except
Returns the set difference, which means the elements of one collection that do not appear in a second collection.
Method Syntax
// Except
var numbers1 = new int[] { 1, 2, 3, 4, 5 };
var numbers2 = new int[] { 4, 5, 6, 7, 8 };
var except = numbers1.Except(numbers2);
// except = { 1, 2, 3 }
Query Syntax
// Not applicable.
Intersect
Returns the set intersection, which means elements that appear in each of two collections.
Method Syntax
// Intersect
var numbers1 = new int[] { 1, 2, 3, 4, 5 };
var numbers2 = new int[] { 4, 5, 6, 7, 8 };
var intersect = numbers1.Intersect(numbers2);
// intersect = { 4, 5 }
Query Syntax
// Not applicable.
Union
Returns the set union, which means unique elements that appear in either of two collections.
Method Syntax
// Union
var numbers1 = new int[] { 1, 2, 3, 4, 5 };
var numbers2 = new int[] { 4, 5, 6, 7, 8 };
var union = numbers1.Union(numbers2);
// union = { 1, 2, 3, 4, 5, 6, 7, 8 }
Query Syntax
// Not applicable.