Can LINQ be used to find gaps in a sorted list?

后端 未结 7 1194
攒了一身酷
攒了一身酷 2020-12-13 04:22

Is it possible for me to use LINQ in a way that allows me to determine that \"9\" is the first missing value in the sorted list without using a for-loop and comparing each

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 05:19

    (abatishchev beat me to the punch, but his answer is better anyway. However, since alternate solutions to the same problem can be fun, I am still posting this.)

    Hackity hack hack. But working, if you really want to do this. Performance will be awful, because this technique will not stop when it finds the answer -- it will always loop over every number! But it will work:

    public static int FindFirstMissing(IEnumerable sequence)
    {
        bool found = false;
    
        int agg = sequence.Aggregate((aggregate, next) => {
            if (found)
                return aggregate;
    
            if (next - aggregate != 1) {
                found = true;
                return aggregate + 1;
            }
    
            return next;
        });
    
        if (!found)
            throw new ArgumentException("sequence", "Contains no missing numbers.");
    
        return agg;
    }
    

提交回复
热议问题