I have a collection of int IDs ranged 0 - 127 called idCollection
I need to iterate through and assign the next available ID from this range after the highest one in this collection. But I also want to iterate back through this collection once I reach 127 and take the next available ID, filling in any gaps.
The below seems to get me max ID + 1 until 127...
_maxId = GetMaxId(idCollection);
while (idCollection.Any(id => id == maxId && maxId != 127)
{
_maxId++;
}
if (_maxId == 127)
{
// Fail
}
private int GetMaxId()
{
return idCollection.Any()
? idCollection.Max()
: 0;
}
The problem I am struggling with is, how can I loop back after to fill in any gaps?
If the list is sorted, this might work
public int GetNext(List<int> list)
{
if(list == null) throw new ArgumentNullException(nameof(list));
var max = list.Count > 0 ? list.Max() : 0;
return max >= 127 ? Enumerable.Range(1, 127).Except(list).First() : max + 1;
}
If its not you could always just call list.Sort();
Also you might want to consider returning null on a full list, or throw an exception
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With