Home > Backend Development > C++ > How Can I Check If One List Contains All Elements of Another in .NET?

How Can I Check If One List Contains All Elements of Another in .NET?

DDD
Release: 2024-12-29 16:33:10
Original
388 people have browsed it

How Can I Check If One List Contains All Elements of Another in .NET?

Determining If One List Contains All Elements of Another in .NET

The LINQ extension method Except can be employed to ascertain whether a list contains all elements of another list. By contrasting the two lists, we can determine if the first list lacks any elements present in the second. This approach is particularly convenient in .NET 3.5 or later versions.

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

This extended ContainsAllItems method operates generically for any sequence type(IEnumerable), making it applicable to a diverse range of collections. The Except method removes elements from b that are also found in a, leaving only those elements unique to b. By then utilizing the Any method, we ascertain if any elements remain in the result, effectively determining if a contains all elements of b.

In summary, the ContainsAllItems method provides a concise and efficient mechanism for verifying the presence of all elements from one list within another, leveraging the capabilities of LINQ to simplify this common operation.

The above is the detailed content of How Can I Check If One List Contains All Elements of Another in .NET?. 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