I’ve previously done a lot of development using Stored Procs to do all the data modifications.
But I now need to use LINQ To SQL and a basic fundamental task has me stumped.
I have a class called Book (Title, Author , etc). A number of books are instantiated and added to
public ObservableCollection Books
So far so good, I can see that it holds valid books in its collection.
I have a function DeleteOldestBook() which simply gets the first Book in Books , and deletes. This is where I run into trouble.
I try and select
Book BookToDelete = Books.Take(1) as Book;
but it always returns NULL.
I’ve managed a hacky workaround :
var AllBooks = from BookToDelete in Books select BookToDelete;
foreach (Book BookToDelete in AllBooks)
{
// BookToDelete.dostuff takes place ...
break; // only do 1
}
But this is awful and I know there’s something simple I’ve missed.
Any ideas from the LINQ experts? Let me know you if you need more code.
Thanks in advance
Takewill return a collection with n elements in it. You still need to iterate over that collection. In your case, the collection size is 1.Firstwill return the first item in the collection.Extra Credit
If your collection is not already sorted use
OrderBy