Linq声明返回下一个ID

Maj*_*jid 1 c# linq list

我有BooksPK的列表Id和一些Books可能删除.例如这个列表Id:

1 2 5 6 8

现在我需要一个linq语句来返回下一个插入ID(例如"3")

我试过这段代码,但总是return"1":

 public int GetNextRecordId()
    {
        List<Book> books = getAll();
        int counted = books.Count();
        foreach (Book b in books)
        {
            if (books.Where(book => book.Id == (b.Id + 1)) == null)
                return b.Id + 1;
        }
        return 1;
    }
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

Gje*_*ema 5

我立刻注意到的一件事是,这永远不会是真的:

books.Where(book => book.Id == (b.Id + 1)) == null
Run Code Online (Sandbox Code Playgroud)

如果找不到匹配项,Where调用将返回一个空的枚举.从那里开始.

试试这个:

!books.Where(book => book.Id == (b.Id + 1)).Any()
Run Code Online (Sandbox Code Playgroud)