.NET 是否有办法检查列表 a 是否包含列表 b 中的所有项目? [英] Does .NET have a way to check if List a contains all items in List b?

查看:30
本文介绍了.NET 是否有办法检查列表 a 是否包含列表 b 中的所有项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

namespace ListHelper
{
    public class ListHelper<T>
    {
        public static bool ContainsAllItems(List<T> a, List<T> b)
        {
            return b.TrueForAll(delegate(T t)
            {
                return a.Contains(t);
            });
        }
    }
}

其目的是确定一个 List 是否包含另一个 List 的所有元素.在我看来,像这样的东西已经内置到 .NET 中了,是这样吗,我是否在重复功能?

The purpose of which is to determine if a List contains all the elements of another list. It would appear to me that something like this would be built into .NET already, is that the case and am I duplicating functionality?

我很抱歉没有预先说明我在 Mono 2.4.2 版上使用此代码.

My apologies for not stating up front that I'm using this code on Mono version 2.4.2.

推荐答案

如果您使用 .NET 3.5,这很容易:

If you're using .NET 3.5, it's easy:

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

这会检查 b 中是否有任何不在 a 中的元素 - 然后反转结果.

This checks whether there are any elements in b which aren't in a - and then inverts the result.

请注意,使 method 泛型而不是类会稍微更传统,并且没有理由要求 List 而不是 IEnumerable - 所以这可能是首选:

Note that it would be slightly more conventional to make the method generic rather than the class, and there's no reason to require List<T> instead of IEnumerable<T> - so this would probably be preferred:

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

这篇关于.NET 是否有办法检查列表 a 是否包含列表 b 中的所有项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆