【问题标题】:Check if all elements in List1<T> are in List2<T> C#检查 List1<T> 中的所有元素是否都在 List2<T> C#
【发布时间】:2012-01-10 12:05:57
【问题描述】:

是否有可能知道或检查 List1 中的所有元素是否都是 List2 的一部分? 例如,如果我有

List1 = { 1,2,3,4 }

List2 = { 1,2,3,5,6,4 }

如果列表 1 中的所有元素都在列表 2 中,我想获得 True,否则为 False

注意:没有 ForLoop

列表可以是整数、字符串等的列表

【问题讨论】:

标签: c# list


【解决方案1】:
using System.Linq;

bool allInList2 = !List1.Except(List2).Any();

【讨论】:

    【解决方案2】:

    您可以使用Intersect 方法。

    那么如果结果与List1 的长度相同,你就知道它的所有元素都包含在List2 中。

    【讨论】:

      【解决方案3】:

      您可以像这样使用HashSet.IsProperSubsetOf(或IsProperSupersetOf)方法:

      var hashset1 = new HashSet<int>(list1);
      if (hashset1.IsProperSubsetOf(list2)) ...
      

      【讨论】:

        【解决方案4】:

        最佳性能 LINQ 解决方案

        此代码示例
        - 检查b中是否有任何不在a中的元素
        - 然后反转结果

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

        最初找到的解决方案here

        【讨论】:

          【解决方案5】:
          List<int> list1 = new List<int>() { 1, 2, 3, 4 };
          List<int> list2 = new List<int>() { 1, 2, 3, 5, 6, 4 };
          
          list1.All(x => list2.Contains(x));
          

          【讨论】:

          • 完美,但我认为您在 lambda 上输入错误 list1,您必须为 list2 更改它:list1.All(x => list2.Contains(x));
          【解决方案6】:

          使用Intersect LINQ 方法:

          List1.Intersect(List2).Count() == List1.Count()
          

          请注意,这确实归结为迭代两个列表 - 没有办法!

          【讨论】:

            【解决方案7】:

            创建这些列表的intersection 并仅查询该交集结果列表。
            当然,内部有一个循环(并且必须是任何给定的解决方案)

            HTH

            【讨论】:

              【解决方案8】:
              bool value = !(l1.Any(item => !l2.Contains(item)));
              

              【讨论】:

              • 他不想要value,而是!value ;)
              • 如果 list1 的任何成员出现在 list2 中或者我遗漏了什么,Haris 你的解决方案将返回 true?
              • 小提示可以简化您过于复杂的表达式:!list.Any(x =&gt; condition) == list.All(x =&gt; !condition)
              【解决方案9】:

              扩展方法,长版:

              public static IsSubetOf (this IEnumerable coll1, IEnumerable coll2)
              {
                foreach (var elem in coll1)
                {
                  if (!coll2.Contains (elem))
                  {
                    return false;
                  }
                }
              
                return true;
              }
              

              短版:

              public static IsSubetOf (this IEnumerable<T> coll1, IEnumerable<T> coll2)
              {
                return !coll1.Any (x => !coll2.Contains (x));
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2020-01-09
                • 1970-01-01
                • 1970-01-01
                • 2012-02-08
                • 1970-01-01
                • 2020-11-12
                • 1970-01-01
                • 2018-07-07
                相关资源
                最近更新 更多