I got a simple List of ints.
List myInts = new List();
myInts.Add(0);
myInts.Add(1);
myInts.Add(4);
myInts.Add(6);
myInts.Add(24);
You basically want the first element from the sequence 0..int.MaxValue
that is not contained in myInts
:
int? firstAvailable = Enumerable.Range(0, int.MaxValue)
.Except(myInts)
.FirstOrDefault();
Edit in response to comment:
There is no performance penalty here to iterate up to int.MaxValue
. What Linq is going to to internally is create a hashtable for myInts
and then begin iterating over the sequence created by Enumerable.Range()
- once the first item not contained in the hashtable is found that integer is yielded by the Except()
method and returned by FirstOrDefault()
- after which the iteration stops. This means the overall effort is O(n) for creating the hashtable and then worst case O(n) for iterating over the sequence where n is the number of integers in myInts
.
For more on Except()
see i.e. Jon Skeet's EduLinq series: Reimplementing LINQ to Objects: Part 17 - Except
Well, if the list is ordered from smallest to largest and contains values from 0 to positive infinity, you could simply access the i-th element. if (myInts[i] != i) return i;
which would be essentially the same, but doesn't necessitate iterating through the list for each and every Contains
check (the Contains method iterates through the list, turning your algorithm into an O(n-squared) rather than O(n)).