首页 > 解决方案 > C# - 从集合中分配整数 ID 后如何循环?

问题描述

我有一个名为 0 - 127 的 int ID 集合idCollection

我需要遍历并在此集合中的最高 ID 之后分配此范围内的下一个可用 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;
}

我正在努力解决的问题是,我怎样才能在填补任何空白后回过头来?

标签: c#linqcollections

解决方案


如果列表已排序,这可能有效

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,或抛出异常


推荐阅读