c# Comparing List<T> (s) using Linq

本文关键字:Linq using Comparing List lt gt | 更新日期: 2023-09-27 18:34:01

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

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

c# Comparing List<T> (s) using Linq

只需使用联合扩展方法,如下所示:

// 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(); 

如果你想直接组合列表,.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)即可。

这可以解决问题:

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