Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find next incremental value not in existing list using linq

Tags:

c#

linq

I have two methods in an IntExtensions class to help generate the next available incremental value (which is not in a list of existing integers which need to be excluded). I dont think I'm addressing the NextIncrementalValueNotInList method in the best way and am wondering if I can better use linq to return the next available int?

public static bool IsInList(this int value, List<int> ListOfIntegers) {
    if (ListOfIntegers.Contains(value))
        return true;

    return false;
}

public static int NextIncrementalValueNotInList(this int value, 
                                                List<int> ListOfIntegers) {

        int maxResult;
        maxResult = ListOfIntegers.Max() + 1;

        for (int i = value; i <= maxResult; i++)
        {
            if (!(i.IsInList(ListOfIntegers)))
            {
                return i;
            }
        }
        return maxResult;
    }
like image 911
D C Avatar asked Nov 24 '25 03:11

D C


1 Answers

Using linq your method will look like:

return IEnumerable.Range(1, ListOfIntegers.Count + 1)
                  .Except(ListOfIntegers)
                  .First();
like image 153
Nikita B Avatar answered Nov 26 '25 17:11

Nikita B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!