【问题标题】:Compare two lists to search common items比较两个列表以搜索常见项目
【发布时间】:2012-07-31 12:24:16
【问题描述】:
List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5

如何从一个列表中获取同时存在于第二个列表中的所有元素?

在这种情况下应该是:1, 4

我当然会谈论没有 foreach 的方法。而是 linq 查询

【问题讨论】:

    标签: c# linq comparison


    【解决方案1】:

    您可以使用Intersect 方法。

    var result = one.Intersect(second);
    

    示例:

    void Main()
    {
        List<int> one = new List<int>() {1, 3, 4, 6, 7};
        List<int> second = new List<int>() {1, 2, 4, 5};
    
        foreach(int r in one.Intersect(second))
            Console.WriteLine(r);
    }
    

    输出:

    1
    4

    【讨论】:

      【解决方案2】:
      static void Main(string[] args)
              {
                  List<int> one = new List<int>() { 1, 3, 4, 6, 7 };
                  List<int> second = new List<int>() { 1, 2, 4, 5 };
      
                  var result = one.Intersect(second);
      
                  if (result.Count() > 0)
                      result.ToList().ForEach(t => Console.WriteLine(t));
                  else
                      Console.WriteLine("No elements is common!");
      
                  Console.ReadLine();
              }
      

      【讨论】:

        猜你喜欢
        • 2011-07-13
        • 1970-01-01
        • 2011-01-24
        • 1970-01-01
        • 2015-08-31
        • 1970-01-01
        • 2016-03-06
        • 2018-05-01
        相关资源
        最近更新 更多