Search code examples
c#listlinq-query-syntax

Get minimum available number in list of integers


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?


Solution

  • 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 };