Lesson 18/31

Tutorials LINQ Mastery

Union, Intersect, Except: Set theory in C#

On this page

Set Operations

LINQ provides native implementations for classic mathematical set operations. These are invaluable for comparing lists or merging data sources.

1. Union (Merge and Unique)

Combines two sequences and removes duplicates. It's different from Concat (which just appends everything). **Architect Note:** Like Distinct, Union uses a internal HashSet and is an O(N+M) operation.

2. Intersect (The Common Ground)

Returns only the elements that appear in BOTH sequences. Perfect for finding 'Common Friends' or 'Shared Interests' between users.

3. Except (The Difference)

Returns elements from the first sequence that do NOT appear in the second sequence. **Use Case:** Find 'Inactive Users' by taking (All Users) Except (Recent Logins).

3. Architect Insight

Q: "Do these work on objects?"

Architect Answer: "Only if you implement GetHashCode and Equals correctly. If you don't want to change your class, use the **'By'** variants (added in .NET 6): UnionBy, IntersectBy, and ExceptBy. These allow you to compare based on a specific key (like Id) without custom comparers."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

LINQ Mastery
Course syllabus
General
1. Core Foundations
2. Filtering & Transformation
3. Aggregation & Quantifiers
4. Ordering & Partitioning
5. Sets & Lookups
6. Join & Grouping
7. Advanced Providers & Parallelism
8. Real-world Performance & Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details