Daniel Williams Daniel Williams - 4 months ago 65
C# Question

get next available integer using LINQ

Say I have a list of integers:

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


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.

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

var nextAvailable = myInts.SomeCoolLinqMethod();


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

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.

Answer Source
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;
    }
}

Usage:

var nextAvailable = myInts.SomeCoolLinqMethod();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download