1

I have a list with the elements [1,2,3,4,5].

If I have another list that contains elements of the mainlist such as [1,2] or [2,4,5], what's an efficient way to generate new lists with the missing numbers, so that:

[1, 2] utilizing [1,2,3,4,5] would give [3, 4 ,5]

[2, 4, 5] utilizing [1,2,3,4,5] would give [1, 3]

I was thinking of using a nested for-loop to check, but I was wondering if there's a more efficient way or built-in function that can be used in C#.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
karamazovbros
  • 950
  • 1
  • 11
  • 40

2 Answers2

5

You could try .Except. Docs

var list1 = new List<int> { 1, 2, 3, 4, 5 };
var list2 = new List<int> { 1, 3, 5 };

var missing = list1.Except(list2).ToList();

missing.ForEach(i => Console.Write("{0}\t", i));

>> 2    4
Loocid
  • 6,112
  • 1
  • 24
  • 42
0

You could try a HashSet (MSDN)

var hash = new HashSet<int>(new int[] {1, 2});
var list = new List<int> {1, 2, 3, 4, 5};
var missing = list.Where(x => !hash.Contains(x)); // 3, 4, 5;

Good thing about using a HashSet is that Contains should be an O(1) operation.

Tarek
  • 1,219
  • 13
  • 18