我有一个范围为0-127的int ID集合,称为idCollection
我需要遍历并分配此集合中最高编号之后的该范围内的下一个可用ID。但是,我也想在我达到127并使用下一个可用ID时再遍历此集合,以填补所有空白。
下面似乎让我最大ID +1直到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;
}
我苦苦挣扎的问题是,如何填补空白后又回头?
最佳答案
如果列表已排序,则可能有效
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;
}
如果不是,您可以随时致电
list.Sort();
另外,您可能要考虑在完整列表上返回null或引发异常