Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to loop back around after assigning integer IDs from a collection?

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?

like image 694
mb1231 Avatar asked Dec 06 '25 22:12

mb1231


1 Answers

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

like image 63
TheGeneral Avatar answered Dec 08 '25 11:12

TheGeneral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!