Home > Backend Development > C++ > Does .NET Offer a Built-in Function to Check if One List Contains All Items from Another?

Does .NET Offer a Built-in Function to Check if One List Contains All Items from Another?

DDD
Release: 2024-12-30 13:52:14
Original
322 people have browsed it

Does .NET Offer a Built-in Function to Check if One List Contains All Items from Another?

Does .NET Have an Inbuilt Function to Check if List a Contains All Items in List b?

The purpose of this question is to determine if .NET provides an inbuilt functionality to ascertain whether one list contains all the elements of another list.

The provided sample code attempts to fulfill this purpose by iterating through the second list and checking if each element is present in the first list. This approach works, but one wonders if such functionality already exists within .NET.

Answer:

For .NET version 3.5 and above, such a function is indeed available:

public static bool ContainsAllItems<T>(List<T> a, List<T> b)
{
    return !b.Except(a).Any();
}
Copy after login

This code compares the elements in list b with those in list a, returning true only if all elements in b are also present in a.

Alternative Implementation:

A more conventional implementation would involve declaring the method as generic and accepting an IEnumerable instead of a specific type (List):

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

Using this approach, you can easily check if one list contains all the elements of another using:

IEnumerable<int> a = new List<int> { 1, 2, 3, 4 };
IEnumerable<int> b = new List<int> { 2, 4, 6, 8 };

bool containsAll = a.ContainsAllItems(b);  // False
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template