.NET 有办法检查列表 a 是否包含列表 b 中的所有项目吗?

问题描述 投票:0回答:6

我有以下方法:

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 中了,是这样吗?我是否在重复功能?

编辑:很抱歉没有预先声明我在 Mono 版本 2.4.2 上使用此代码。

c# .net list generics mono
6个回答
208
投票

如果您使用 .NET 3.5,这很简单:

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

这会检查

b
中是否存在
a
中没有的元素 - 然后反转结果。

请注意,使 method 通用而不是类更传统,并且没有理由要求

List<T>
而不是
IEnumerable<T>
- 所以这可能是首选:

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

49
投票

包含在 .NET 4 中:Enumerable.All

public static bool ContainsAll<T>(IEnumerable<T> source, IEnumerable<T> values)
{
    return values.All(value => source.Contains(value));
}

36
投票

只是为了好玩,@JonSkeet 的 answer 作为扩展方法:

/// <summary>
/// Does a list contain all values of another list?
/// </summary>
/// <remarks>Needs .NET 3.5 or greater.  Source:  https://stackoverflow.com/a/1520664/1037948 </remarks>
/// <typeparam name="T">list value type</typeparam>
/// <param name="containingList">the larger list we're checking in</param>
/// <param name="lookupList">the list to look for in the containing list</param>
/// <returns>true if it has everything</returns>
public static bool ContainsAll<T>(this IEnumerable<T> containingList, IEnumerable<T> lookupList) {
    return ! lookupList.Except(containingList).Any();
}

3
投票

我知道一种使用 LinQ 方法的方法。读起来有点奇怪,但效果很好

var motherList = new List<string> { "Hello", "World", "User };
var sonList = new List<string> { "Hello", "User" };

你想检查 sonList 是否完全在 motherList 中

为此:

sonList.All(str => moterList.Any(word => word == str));

// Reading literally, would be like "For each of all items 
// in sonList, test if it's in motherList

请检查一下,看看是否也能正常工作。希望有帮助;-)


0
投票
    public static bool ContainsAll<T>(this IEnumerable<T> containingList, IEnumerable<T> lookupList)
    {
        return containingList.Intersect(lookupList).Count() == lookupList.Count();
    }

-1
投票

您也可以使用另一种方式。覆盖等于并使用它

public bool ContainsAll(List<T> a,List<T> check)
{
   list l = new List<T>(check);
   foreach(T _t in a)
   {
      if(check.Contains(t))
      {
         check.Remove(t);
         if(check.Count == 0)
         {
            return true;
         }
      }
      return false;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.