Get minimum available number in list of integers

196 views Asked by At

How to get minimum available number in list of integers with LINQ? Number can not be lower than 10.

List<int> numbers = new List<int>() { 10, 11, 12, 22, 23 };

I want to return 13 in this case.

List<int> numbers1 = new List<int>() { 11, 12, 22, 23 };

I want to return 10 in this case

How can I do it with LINQ?

2

There are 2 answers

3
Enigmativity On BEST ANSWER

I'd use this:

List<int> numbers = new List<int>() { 11, 12, 22, 23 };

int result = Enumerable.Range(10, numbers.Count + 1).First(x => !numbers.Contains(x));

The use of numbers.Count + 1 handles the case where List<int> numbers = new List<int>() { 10, 11, 12, 13, 14, 15 };

0
canton7 On

If the input list is always sorted, you can take advantage of this and do a simple linear search:

List<int> numbers = new List<int>() { 11, 12, 13, 14 };
int result = numbers
    .Zip(
        numbers.Skip(1).Concat(new[] { int.MaxValue }),
        (a, b) => (next: a+1, b))
    .FirstOrDefault(x => x.next != x.b)
    .next;

This is more ugly than @Enigmativity's solution, but it has the advantage of being linear rather than quadratic, which will have an impact if the list of numbers is large.

Personally, I'd just have written this as a cheap linear for loop:

for (int i = 0; i < numbers.Count - 1; i++)
{
    int next = numbers[i] + 1;
    if (next != numbers[i + 1])
    {
        return next;
    }
}
return numbers[numbers.Count - 1] + 1;