(I answered this question on StackOverflow, just copying it here...)
If you want to check if your list contains all numbers from 1 to (row-1), you could use a HashSet
like this:
var hashSet = new HashSet(myList.Where(item => item >= 1 && item < row))
This adds all "relevant" items of the list to the Set.
Since a HashSet
contains every item at most once, you can check the Count
of it to ensure, all numbers are present, like:
var check = hashSet.Count == (row - 1)
Regarding performance, this might be more efficient than your solution, since the list needs only to be iterated once (in your solution, you have row-1
iterations, one for every Contains
operation). And adding to a HashSet
is considered a O(1) operation.
Note: The major drawback of this solution is that its not immediately apparent what it does. So consider adding a comment to it.
Another, more readable approach would be to explicitely check, if all numbers are contained in the Set, like
var hashSet = new HashSet(myList);
var check = Enumerable.Range(1, row).All(number => hashSet.Contains(number));
If you consider row
to be a constant the asymptotical time will be the same: O(n) for constructing the HashSet
, and O(1)*O(1)=O(1) for the check itself (first O(1) for the constant number of "rows" to be checked, second O(1) for the Contains
function...)
do...while
for this to make any real sense. – Ant P Dec 29 '13 at 17:17