Home >Backend Development >C++ >Does .NET Offer a Built-in Way to Check if One List Contains All Elements of Another?

Does .NET Offer a Built-in Way to Check if One List Contains All Elements of Another?

Susan Sarandon
Susan SarandonOriginal
2025-01-01 01:14:18540browse

Does .NET Offer a Built-in Way to Check if One List Contains All Elements of Another?

Does .NET Have a Built-in Method to Check if One List Contains All Items in Another?

Problem:

You have a method (ContainsAllItems) that determines if List a contains all the elements of List b. You wonder if this functionality is already built into .NET, potentially duplicating your effort.

Answer:

Yes, in .NET 3.5 and later, you can use the following method:

public static class LinqExtras
{
    public static bool ContainsAllItems<T>(this IEnumerable<T> a, IEnumerable<T> b)
    {
        return !b.Except(a).Any();
    }
}

Usage:

List<int> a = new List<int>() { 1, 2, 3, 4 };
List<int> b = new List<int>() { 2, 3 };

bool result = a.ContainsAllItems(b); // True

This method performs a set difference between b and a (b.Except(a)), which returns the elements in b that are not in a. The Any() method is then used to check if there are any elements in the set difference, and the result is inverted to determine if a contains all items in b.

Note:

The original ContainsAllItems method is also a valid solution but is slightly less efficient than the approach using LINQ. The LINQ version takes advantage of lazy evaluation, potentially performing less work if the lists have a large number of items.

The above is the detailed content of Does .NET Offer a Built-in Way to Check if One List Contains All Elements of Another?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn