views:

59

answers:

3

What's the most efficient way to get a first free spot from sorted query returning int collection ?

eg.: {1,2,3,4,6} | result.: 5

At the moment I am using foreach and counter that compares current value from sorted quety.ToList() which takes about 600ms on 100 000 records.

+1  A: 

Unless you multithread it, reading one at a time is your fastest solution since this is an O(n) problem.

Yuriy Faktorovich
+1  A: 

I am not sure how you would write it in LINQ, but I suppose a binary search could be faster in this way - starting from the middle, comparing the index with value - if they are equal, continue in the right half, otherwise in the left half etc.

Even if you're starting from an index start_index which is not 1, you can simply compare the value with index increased by start_index.

Thomas Wanner
That is if you have the index.
Yuriy Faktorovich
You have the index = you can access the collection at a concrete index ? If you can't do that then you're probably right that it's O(n) ;)
Thomas Wanner
+1  A: 

Why do you use ToList()? Turning it to a list renders the whole IEnumerable idea absolute and you might lose some performance there. Why not iterate with foreach over the IQueryable and find the first missing memeber?

VitalyB
Tryed it , it takes twice as much time.
Jacob
Err... It took LESS TIME with ToList()?
VitalyB