Convert a Type to a Generic IEnumerable


Use AsEnumerable<TSource> to return the argument typed as a generic IEnumerable.

In this example, LINQ to SQL (using the default generic Query) would try to convert the query to SQL and execute it on the server. But the where clause references a user-defined client-side method (isValidProduct), which cannot be converted to SQL.

The solution is to specify the client-side generic IEnumerable<T> implementation of where to replace the generic IQueryable<T>. You do this by invoking the AsEnumerable<TSource> operator.

        private bool isValidProduct(Product prod)
            return prod.ProductName.LastIndexOf('C') == 0;

        void ConvertToIEnumerable()
            Northwnd db = new Northwnd(@"c:\test\northwnd.mdf");
            Program pg = new Program();
            var prodQuery =
                from prod in db.Products.AsEnumerable()
                where isValidProduct(prod)
                select prod;

Query Examples