.NET
C#
List
Collection
Programming

Does .NET have a way to check if List a contains all items in List b?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Yes, .NET has several ways to check whether one list contains all elements of another. The best approach depends on whether duplicates matter and how large the lists are. For small lists, LINQ is concise, while large lists benefit from HashSet or counting dictionaries.

Basic LINQ Check

If duplicates do not matter, the simplest expression is All plus Contains.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5var listA = new List<int> { 1, 2, 3, 4, 5 };
6var listB = new List<int> { 2, 4 };
7
8bool containsAll = listB.All(item => listA.Contains(item));
9Console.WriteLine(containsAll); // True

This is readable but can be slow for large inputs because Contains on List<T> is linear.

Faster Check with HashSet<T>

For bigger collections where duplicates still do not matter, convert list A to a hash set.

csharp
1var listA = new List<string> { "us", "ca", "mx", "br" };
2var listB = new List<string> { "ca", "mx" };
3
4var setA = new HashSet<string>(listA);
5bool containsAll = listB.All(setA.Contains);
6
7Console.WriteLine(containsAll); // True

Average lookup becomes constant time, so overall performance improves significantly.

When Duplicates Matter

If list B requires multiplicity, a set is not enough. For example, list B might require two occurrences of value 2. Use frequency maps.

csharp
1using System.Collections.Generic;
2using System.Linq;
3
4static bool ContainsAllWithCounts<T>(IEnumerable<T> source, IEnumerable<T> required)
5{
6    var counts = source
7        .GroupBy(x => x)
8        .ToDictionary(g => g.Key, g => g.Count());
9
10    foreach (var item in required)
11    {
12        if (!counts.TryGetValue(item, out int count) || count == 0)
13            return false;
14
15        counts[item] = count - 1;
16    }
17
18    return true;
19}
20
21var a = new List<int> { 1, 2, 2, 3 };
22var b = new List<int> { 2, 2 };
23Console.WriteLine(ContainsAllWithCounts(a, b)); // True

This handles multiset containment correctly.

Custom Types and Comparers

For custom objects, equality semantics determine whether containment works as expected. Implement IEquatable<T> or pass an IEqualityComparer<T>.

csharp
1record User(string Email);
2
3var listA = new List<User> { new("[email protected]") };
4var listB = new List<User> { new("[email protected]") };
5
6var comparer = StringComparer.OrdinalIgnoreCase;
7var emails = new HashSet<string>(listA.Select(u => u.Email), comparer);
8bool containsAll = listB.All(u => emails.Contains(u.Email));
9
10Console.WriteLine(containsAll); // True

Without proper comparers, logically equal values may fail containment checks.

Alternative Set Semantics with Except

If duplicates are irrelevant and you want quick failure diagnostics, Except can help show missing elements.

csharp
var missing = listB.Except(listA).ToList();
bool containsAll = missing.Count == 0;

This is useful in validation code where you want to report exactly which required values were absent.

Complexity and Practical Guidance

Rough complexity:

  • All plus List.Contains: up to n * m
  • HashSet lookup flow: about n + m
  • count dictionary flow: about n + m

For very large lists, these differences are meaningful. For tiny lists, readability often matters more than micro-optimization.

Test Cases You Should Include

Containment logic can fail silently with edge cases. Unit tests should cover:

  • empty required list
  • required list larger than source
  • duplicate-sensitive scenarios
  • custom comparer behavior
  • null handling where allowed

This keeps behavior explicit when requirements evolve.

Common Pitfalls

  • Ignoring duplicates can return false positives in business logic that depends on counts.
  • Using List<T>.Contains inside loops on large data can degrade performance quickly.
  • Relying on default equality for custom classes can cause unexpected mismatches.
  • Treating null values casually can break comparisons if not handled deliberately.
  • Mixing culture-sensitive and ordinal string comparisons may produce inconsistent results.

Summary

  • .NET supports containment checks with simple LINQ and optimized set-based approaches.
  • Use HashSet<T> when performance matters and duplicates are irrelevant.
  • Use count-based logic when multiplicity is part of correctness.
  • Define equality semantics clearly for custom types.
  • Pick method by data size and required behavior, not by syntax preference.

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
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms