【问题标题】:Check if list contains another list. C#检查列表是否包含另一个列表。 C#
【发布时间】:2014-01-25 20:49:04
【问题描述】:

编辑,只是说 ContainsAllItem 中的注释解释得最好。

对不起,我知道以前有人问过这个问题,但我只是没听懂。 好的,所以我想检查一个列表是否包含另一个列表中的所有项目 WITHOUT 重叠,以及根据类字符串、名称变量(称为 itemname 并且它是公共的)比较项目。

public class Item
{
    public string itemname;
}

所以基本上,有一个带有项目列表的类(比如说.. A 类),以及一个检查 A 类项目列表的函数,然后将其与另一个列表进行比较(我们称之为 B) ,但通过 itemname 变量而不是整个项目进行比较。

最重要的是,您能否详细解释一下它的作用。

那么函数/类现在的样子。

public class SomeClass
{
    public List<Item> myItems = new List<Item>();

    public bool ContainsAllItems(List<Item> B)
    {
        //Make a function that compares the to lists by itemname and only returns true if the myItems list contains ALL, items in list b.
        //Also could you explain how it works.
    }
}

【问题讨论】:

标签: c# .net


【解决方案1】:

我还没有检查这个首选项,但 linq 确实有 except 运算符。

 var x = new int[] {4,5};
 var y = new int[] {1 ,2 ,3 ,4 ,5};   

 y.Except(x).Any(); //true, not all items from y are in x
 x.Except(y).Any(); // false, all items from x are in y

【讨论】:

    【解决方案2】:
    B.All(itB=>myItems.Select(itA=>itA.ItemName).Contains(itB.ItemName))
    

    将在 O(N^2) 时间内运行,但很酷,您只需一行相当难以理解的代码就可以做到这一点。

    【讨论】:

      【解决方案3】:

      这并不完全符合您的要求,但在性能方面您绝对应该使用HashSetIsProperSubsetOf。它可以在更少的时间内完成您想要的工作:

      HashSet<string> a = new HashSet<string>(list1.Select(x => x.itemname));
      HashSet<string> b = new HashSet<string>(list2.Select(x => x.itemname));
      
      a.IsProperSubsetOf(b)
      

      解释: HashSet 使用项目的GetHashCode 值和Equals 方法有效地比较项目。这意味着当它在内部遍历 b 中的值时,不必将其与 a 中的所有其他项目进行比较。它使用哈希码(和内部哈希函数)来检查它是否已经具有该值。

      因为它只对每个项目进行一次检查(每个检查是 O(1)),所以它比检查 a 中的 所有 项目要快得多,这需要 O(n)(对于每个b 中的项目)。

      【讨论】:

      • 你也是从哪里学的这些东西?有什么好的教程、MDSN 或大学吗?
      • @user3210251 是的。 MSDN、StackOverflow、经验、其他团队成员,给我的教程少了,大学时就更少了。
      • @user3210251 =&gt; 是 lambda 表达式的一部分。你可以在这里阅读更多信息:msdn.microsoft.com/en-us/library/bb397687.aspx
      【解决方案4】:

      这是另一种方式。我提供了一种包含和排除列表比较的方法。

      var a = new List<int> { 1, 2, 3, 4, 5 };
      
      var b = new List<int> { 1, 2, 3 };
      
      //Exists in list a but not in b
      var c = (from i 
                  in a 
               let found = b.Any(j => j == i) 
               where !found select i)
               .ToList();
      
      //Exists in both lists
      var d = (from i 
                  in a  
               let found = b.Any(j => j == i) 
               where found select i)
               .ToList();
      

      【讨论】:

        猜你喜欢
        • 2017-01-13
        • 1970-01-01
        • 1970-01-01
        • 2012-08-01
        • 2022-11-21
        • 1970-01-01
        • 2021-04-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多