1

I want to compare two collections. I believe that I am doing it the long way (codewise). I want to find what numbers might be missing from a collection when compared to another collection. Order is unimportant.

  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);
        }
    }
}
Paul Stanley
  • 1,999
  • 1
  • 22
  • 60

3 Answers3

4

Just use the Union extension method as follow:

// 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(); 
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
2

If you want to directly combine the lists, a .Union() would certainly work. If you just want to find the values that are missing from one list to another, do an .Except(), e.g.

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

Where result will return { 2, 3 }. If you then wanted to add result to x, simply do an x.AddRange(result).

Alex R.
  • 185
  • 1
  • 7
1

This does the trick:

x.AddRange(y.Where(num => !x.Contains(num)));
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142