代码之家  ›  专栏  ›  技术社区  ›  Matt Haley

.NET是否有方法检查列表A是否包含列表B中的所有项?

  •  79
  • Matt Haley  · 技术社区  · 15 年前

    我有以下方法:

    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);
                });
            }
        }
    }
    

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

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

    4 回复  |  直到 6 年前
        1
  •  149
  •   RMalke    6 年前

    如果您使用的是.NET 3.5,那么很容易:

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

    这将检查中是否有任何元素 b 那些不在 a -然后反转结果。

    请注意,使 方法 而不是类,没有理由要求 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();
        }
    }
    
        2
  •  32
  •   Community CDub    8 年前

    只是为了好玩,@jonsket's 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
  •  26
  •   orad    8 年前

    包含在.NET 4中: Enumerable.All

    public static bool ContainsAll<T>(IEnumerable<T> source, IEnumerable<T> values)
    {
        return values.All(value => source.Contains(value));
    }
    
        4
  •  0
  •   Rohit Vipin Mathews    9 年前

    你也可以用另一种方式。重写等于并使用此

    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;
       }
    }