October 2008 Entries

Lazy LINQ and Enumerable Objects

Someone asked me why LINQ operators return an IEnumerable<T> instead of something more useful, like a List<T>. In other words, in the following code:List<Book> books = new List<Book>(); // ... IEnumerable<Book> filteredBooks = books.Where(book => book.Title.StartsWith("R")); ... we started with a List<Book>, so why isn’t the Where operator smart enough to return a new List<Book>, or modify the existing list by removing books that don’t match the Where condition? Let’s talk about modifying the original list. I hope you’ll agree that it would be odd for a query to modify a data source. Imagine sending a SELECT statement to a...