score:6

Accepted answer

Take will return a collection with n elements in it. You still need to iterate over that collection. In your case, the collection size is 1.

First will return the first item in the collection.

Extra Credit

If your collection is not already sorted use OrderBy

Book bookToDelete = Books.OrderBy(b => b.SomeDate).First();

score:6

just use FirstOrDefault():

var firstBook = Books.FirstOrDefault();

If there is no book in the collection, firstBook will be null, otherwise it will be set to the first item.

Typically you would want the first book by some criteria though, if so just use an appropriate Where clause beforehand:

var firstThriller = Books.Where(b => b.Type == "Thriller")
                         .FirstOrDefault();

score:1

Take returns an IEnumerable<T> containing a single element, what you want is:

Books.FirstOrDefault();

Which returns the first element (or null if Books is empty).

score:10

Take() returns an IEnumerable<Book>. As such, your attempt to cast it into a Book fails, returning a null value.

Use Books.First() or Books.FirstOrDefault() instead.

Clarification for Nitpickers: Take() may actually return an IQuerable<Book> if Books came directly from a DataContext.

score:3

I would just use

Books.First();

Instead of

Take(1);

The Take Extension method returns IQueryable<T> and you're trying to cast as T (Book). This is why you always get null.

score:2

Yes, you missed the First() extension method:

Book BookToDelete = Books.First();

Note that Take(int) returns a sequence of Books (IQueryable<T>) - even if that sequence contains just one item in your case. As there is no conversion from IQueryable<T> to T, as will return null.


Related Articles