C# Reference ยท LINQ
LINQ Union(), Intersect() and Except() methods
Reference for LINQ Union, Intersect, Except, their By variants and Concat in C#: duplicates, comparers, ordering, symmetric difference and performance.
Union(), Intersect() and Except() combine two sequences using set logic. Union() returns every distinct element found in either sequence. Intersect() returns the distinct elements found in both. Except() returns the distinct elements of the first sequence that do not appear in the second.
The results are always free of duplicates, even if the inputs contain them. Concat() is the one that does not remove anything: it just appends. Since .NET 6 there are also UnionBy(), IntersectBy() and ExceptBy() that compare by a key.
var all = a.Union(b); var common = a.Intersect(b); var onlyInA = a.Except(b);
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 IEnumerable<T> Union<T>(this IEnumerable<T> first, IEnumerable<T> second); public static IEnumerable<T> Intersect<T>(this IEnumerable<T> first, IEnumerable<T> second); public static IEnumerable<T> Except<T>(this IEnumerable<T> first, IEnumerable<T> second); public static IEnumerable<T> Concat<T>(this IEnumerable<T> first, IEnumerable<T> second); public static IEnumerable<T> ExceptBy<T, TKey>(this IEnumerable<T> first, IEnumerable<TKey> second, Func<T, TKey> keySelector); // Union, Intersect, Except and the By forms each have an IEqualityComparer overload
| Name | Description |
|---|---|
first, second |
The two sequences. |
keySelector |
For the By forms: the key of an element of first (and of second in UnionBy()). IntersectBy() and ExceptBy() take a sequence of keys as the second argument. |
comparer |
Optional IEqualityComparer<T>. |
Returns: a lazy sequence without duplicates (except Concat()).
Errors: ArgumentNullException if an argument is null.
Usage notes
- Order: current .NET returns
Union()elements from the first sequence then the second, andIntersect()andExcept()in the order of the first sequence. Treat that as an implementation detail and sort if order matters. - Complexity: each operator is O(n + m) using a hash set.
Intersect()andExcept()read the second sequence fully (into the set) and stream the first. - Equality: uses
Equals()andGetHashCode(), so reference types without value equality behave like reference comparison. Records, strings, tuples and numbers behave as expected. - Duplicates vanish.
Except()on{1, 1, 2}minusyields1once. If you need to keep duplicates, useWhere(x => !set.Contains(x)). Concat()vsUnion():Concat()keeps duplicates and does no hashing, so it is cheaper.- Not symmetric:
a.Except(b)is not the same asb.Except(a). - Sets as inputs: if the data is already a
HashSet<T>, its ownUnionWith(),IntersectWith()andExceptWith()modify it in place without LINQ. - Comparing sequences, not sets: use
SequenceEqual(), which cares about order and duplicates.
Related
Distinct(),ToHashSet(),Contains(),HashSet<T>- Lessons: LINQ operators, Sets