使用LINQ获取下一个可用的整数 [英] get next available integer using LINQ

查看:60
本文介绍了使用LINQ获取下一个可用的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个整数列表:

List<int> myInts = new List<int>() {1,2,3,5,8,13,21};

我想获得下一个可用的整数,按递增的整数排序.不是最后一个或最高的整数,在这种情况下不是此列表中的下一个整数.在这种情况下,数字为4.

I would like to get the next available integer, ordered by increasing integer. Not the last or highest one, but in this case the next integer that is not in this list. In this case the number is 4.

是否有LINQ语句可以给我这个?如:

Is there a LINQ statement that would give me this? As in:

var nextAvailable = myInts.SomeCoolLinqMethod();

废话.我说答案应该是2,但我的意思是4.对此我表示歉意!

Crap. I said the answer should be 2 but I meant 4. I apologize for that!

例如:假设您负责分发进程ID.您想要获取当前进程ID的列表,并发出下一个ID,但下一个ID不应只是最大值加1.相反,它应该是进程ID的有序列表中的下一个可用列表.您可以从最高的级别开始获得下一个可用,这并不重要.

For example: Imagine that you are responsible for handing out process IDs. You want to get the list of current process IDs, and issue a next one, but the next one should not just be the highest value plus one. Rather, it should be the next one available from an ordered list of process IDs. You could get the next available starting with the highest, it does not really matter.

推荐答案

public static class IntExtensions
{
    public static int? SomeCoolLinqMethod(this IEnumerable<int> ints)
    {
        int counter = ints.Count() > 0 ? ints.First() : -1;

        while (counter < int.MaxValue)
        {
            if (!ints.Contains(++counter)) return counter;
        }

        return null;
    }
}

用法:

var nextAvailable = myInts.SomeCoolLinqMethod();

这篇关于使用LINQ获取下一个可用的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆