【问题标题】:c# Comparing List<T> (s) using Linqc# 使用 Linq 比较 List<T> (s)
【发布时间】:2016-02-10 19:21:22
【问题描述】:

我想比较两个集合。我相信我正在做很长的路(代码方面)。我想找出一个集合与另一个集合相比可能缺少哪些数字。顺序不重要。

  class Program
{
    static void Main(string[] args)
    {
       List< int> x = new List<int>() { 1 };
       List< int> y = new List<int>() { 1, 2, 3 };

        //find what numbers (if any) that x needs to  have in order to have  an identical list as y (order not important)

        List<int> missingNumbers = new List<int>();
        foreach (var number in y)
        {
            if (!x.Contains(number))
            {
                missingNumbers.Add(number);
            }
        }
        foreach (var missingNumber in missingNumbers)
        {
            x.Add(missingNumber);
        }
    }
}

【问题讨论】:

  • y.Except(x) ?
  • 重复项呢?
  • 我希望 x 拥有与 y 相同的项目。顺序不重要。
  • 这没有多大意义——你可以做x = new List&lt;int&gt;(); x.AddRange(y)——当然还有更多的东西,只是让 x 和 y 有相同的项目?
  • 按照我的回答使用联合扩展方法。

标签: c# collections


【解决方案1】:

只需使用Union扩展方法如下:

// x will contain 1, 2, 3. 
// No ducplicate will be added 
// and the missing numbers 2 and 3 are added.
x = x.Union(y).ToList(); 

【讨论】:

  • 这不能回答 OP 的问题,即“在 x 中找到 y 中缺少的数字”
  • @Charleh OP 不知道他想要什么 I want x to have the same items as y. order not important.
  • "我想知道缺少哪些数字。然后将它们添加到 x。"由 OP
  • 是的,你一开始是对的,OP 的澄清总是有帮助的 :)
【解决方案2】:

如果您想直接合并列表,.Union() 肯定可以。如果您只想查找从一个列表到另一个列表中缺少的值,请执行.Except(),例如

List<int> x = new List<int>() { 1 };
List<int> y = new List<int>() { 1, 2, 3 };
var result = y.Except(x).ToList();

结果将返回{ 2, 3 }。如果您想将result 添加到x,只需执行x.AddRange(result)。

【讨论】:

    【解决方案3】:

    这就是诀窍:

    x.AddRange(y.Where(num => !x.Contains(num)));
    

    【讨论】:

    • ToList 的意义何在?似乎还缺少)。
    • 这不会删除重复项
    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多