'Add objects from database to a List, using LINQ to SQL

I have a table books and i want to put all of its contents into a List<book> (right now i'am stuck at adding a single element). I tried

public class DataContext
{
    LINQtoSQLDataContext db = new LINQtoSQLDataContext();
    List<book> books = new List<book>();
    public List<book> addBook()
    {
        books.Add((book)from book in db.books where book.bookID == 1 select book);
        return books;
    }
}

But when i try to set it as the source of my wpf dataGrid, it throws an error:

Unable to cast object of type 'System.Data.Linq.DataQuery`1[DataLayer.book]' to type 'DataLayer.book'.

So the question is, how do i properly convert data from the database to a list?



Solution 1:[1]

if I understand your problem correctly, the solution is simpler than expected, try making a where condition like this:

public class DataContext
{
LINQtoSQLDataContext db = new LINQtoSQLDataContext();
List<book> books = new List<book>();
public List<book> addBook()
{
    books = db.book.Where(x => x.bookId == 1).ToList();
    return books;
} 
}

Solution 2:[2]

Just as sr28 pointed out, this will return an array. You could either add the array to the books list. I personally prefer using the method syntax.

I don't really understand why you would add the book to this list. But here you go. Since you already defined books you dont need to return it, you can simply add book to books.

public void AddBook()
{
    var book = db.books.FirstOrDefault(b => b.BookId == 1);
    books.add(book);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vinceenzo
Solution 2