【问题标题】:C# - How to loop back around after assigning integer IDs from a collection?C# - 从集合中分配整数 ID 后如何循环?
【发布时间】:2018-11-01 22:55:20
【问题描述】:

我有一个名为 idCollection 的 int ID 集合,范围为 0 - 127@

我需要遍历并在此集合中的最高 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# linq collections


    【解决方案1】:

    如果列表已排序,这可能会起作用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多