Friday, January 13, 2012

Queryable.Where versus Enumerable.Where

        public ViewResult list1()
        {
            IQueryable<Customer> custs = db.Customers;
            var someCustomers = custs.Where(c => c.lastName.StartsWith("Smith"));
            return View();
        }

        public ViewResult list2()
        {
            IEnumerable<Customer> custs = db.Customers;
            var someCustomers = custs.Where(c => c.lastName.StartsWith("Smith"));
            return View();
        }
I had a mystery for a few minutes the other day when I was testing a snippet of code. I was not getting any records back from list2(), while list1() was functioning like I expected.
 In the test database I was using, all last names were stored in lowercase.

This illustrated the difference between
Queryable.Where (lambda expression converted to an expression tree)
and
 Enumerable.Where. (lambda expression converted to a delegate)

In the first case the filter is executed in the database and is not case sensitive. In the second case, the filter is executed in .NET code using Contains which is case sensitive.

No comments:

Post a Comment