1

我有BooksPK 的列表,其中Id一些Books可能已删除。例如带有这个Ids 的列表:

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

如何解决这个问题?

4

3 回答 3

5

One thing I notice right away is that this will never be true:

books.Where(book => book.Id == (b.Id + 1)) == null

The Where call returns an empty enumerable if it finds no matches. Start from there.

Try this instead:

!books.Where(book => book.Id == (b.Id + 1)).Any()
于 2013-04-21T04:01:10.603 回答
2

如果您有大量书籍,您可能无法像那样将它们全部保存在内存中。而且您当然不想对它们进行循环,其中的Where子句再次迭代它们。你最好依次阅读它们以寻找这样的差距:-

public int GetNextRecordId()
{
    // Cannot load all books into memory ...
    IEnumerable<Book> books = dataContext.Books.OrderBy(b => b.Id);

    int index = 0;
    foreach (var book in books)
    {
      index++;
      if (index < book.Id) return index;
    }
    return index;
}
于 2013-04-21T04:40:59.683 回答
1

我建议这个 linq 查询,如果这个查询在 linq to entites 上运行,查询成本非常低:

var id = books.Select(p => p.Id  + 1).Except(books.Select(p=>p.Id)).First();
于 2013-04-21T04:16:00.137 回答