LINQ
Sequence Comparison
C# Programming
.NET
Data Structures

LINQ Determine if two sequences contains exactly the same elements

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Determining whether two sequences contain exactly the same elements depends on your definition of “same.” You may care about order, duplicate counts, or only unique membership. LINQ provides tools for each case, but using the wrong method produces subtle bugs that pass basic tests.

Core Sections

First decide equality semantics

Common semantics:

  • ordered equality: same items in same order
  • multiset equality: same items with same counts, order irrelevant
  • set equality: same unique items, duplicates ignored

Do not implement code before this decision is explicit. Most defects in sequence comparison come from hidden semantic assumptions.

Ordered equality with SequenceEqual

If order matters, use SequenceEqual.

csharp
1using System;
2using System.Linq;
3
4var a = new[] { 1, 2, 2, 3 };
5var b = new[] { 1, 2, 2, 3 };
6var c = new[] { 2, 1, 2, 3 };
7
8Console.WriteLine(a.SequenceEqual(b)); // true
9Console.WriteLine(a.SequenceEqual(c)); // false

This is efficient and clear when sequence order is part of contract.

Unordered equality with duplicate counts

If order does not matter but multiplicity does, compare grouped counts.

csharp
1using System.Collections.Generic;
2using System.Linq;
3
4bool SameMultiset<T>(IEnumerable<T> left, IEnumerable<T> right)
5{
6    var l = left.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
7    var r = right.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
8
9    return l.Count == r.Count && l.All(kv => r.TryGetValue(kv.Key, out var c) && c == kv.Value);
10}
11
12var x = new[] { 1, 1, 2 };
13var y = new[] { 1, 2, 1 };
14var z = new[] { 1, 2, 2 };
15
16Console.WriteLine(SameMultiset(x, y)); // true
17Console.WriteLine(SameMultiset(x, z)); // false

This pattern preserves duplicate significance.

Set equality when duplicates are irrelevant

If duplicates should be ignored, use set operations.

csharp
1using System.Collections.Generic;
2
3bool SameSet<T>(IEnumerable<T> left, IEnumerable<T> right)
4{
5    return new HashSet<T>(left).SetEquals(right);
6}

Be explicit in naming so callers understand duplicate behavior.

Custom comparer for object sequences

For custom objects, provide equality comparer or override equality members.

csharp
1record User(int Id, string Name);
2
3var u1 = new[] { new User(1, "Ana"), new User(2, "Ben") };
4var u2 = new[] { new User(1, "Ana"), new User(2, "Ben") };
5
6Console.WriteLine(u1.SequenceEqual(u2)); // true with record value equality

For classes without value equality, SequenceEqual can return false even when fields match.

Performance considerations

  • SequenceEqual can short-circuit and stream efficiently.
  • Grouping-based multiset checks allocate dictionaries and scale with unique key count.
  • Sorting both sequences then comparing is another approach but can cost extra time and memory.

Pick method based on semantic correctness first, then optimize if needed.

Testing strategy

For any helper, include tests for:

  • empty sequences
  • different lengths
  • same elements different order
  • duplicate count mismatch
  • null input behavior if applicable

Without explicit tests, future refactors can silently alter equality semantics. If helpers are used in hot code paths, profile with realistic collection sizes and equality comparer costs. In many systems, comparer complexity dominates runtime more than the LINQ operator choice itself. For distributed services, keep comparison semantics documented in API contracts so upstream and downstream components do not disagree on whether duplicates should matter.

For domain entities, implement and test a dedicated comparer so equality logic does not drift between sequence checks and other collection operations.

Common Pitfalls

  • Using SequenceEqual when business logic does not require order sensitivity.
  • Ignoring duplicate counts in domains where multiplicity matters.
  • Comparing complex objects without correct equality semantics.
  • Sorting in place and accidentally mutating caller-owned collections.
  • Naming helpers ambiguously so callers assume different comparison rules.

Summary

  • “Exactly same elements” is ambiguous until order and duplicates are defined.
  • Use SequenceEqual for ordered comparisons.
  • Use grouped counts for unordered comparisons with multiplicity.
  • Use set equality only when duplicate counts are irrelevant.
  • Encode semantics in helper names and tests to prevent regressions.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.