c# - 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;
}
我正在努力解决的问题是,我怎样才能在填补任何空白后回过头来?
解决方案
如果列表已排序,这可能有效
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,或抛出异常
推荐阅读
- telnet - Telnet 内部工作:如果客户端连接到 HTTP 服务器,是否需要 telnet 服务器?
- azure-devops - 如何使用 Visual Studio Code 和 VSTS 对 ARM 模板实施代码审查
- android - RadAutoCompleteTextView 自动完成
- python - 如何监视内部函数返回值
- augmented-reality - 使用 aframe /aframe-ar 在 3D 框中显示文本
- spring - Spring Security基于用户从db中分配的多个角色中选择的角色登录
- html - 我怎么能放
- django - Nginx 不提供静态文件
- php - 从几天开始,Facebook 事件列表不起作用
- mongodb - 当存在自相交时,$geoIntersects 不起作用