How to: Convert a Type to a Generic IEnumerable (LINQ to SQL)

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

Example

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 Function isValidProduct(ByVal prod As Product) As Boolean 
    Return prod.ProductName.LastIndexOf("C") = 0
End Function 

Sub ConvertToIEnumerable()
    Dim db As New Northwnd("c:\northwnd.mdf")
    Dim validProdQuery = _
        From prod In db.Products.AsEnumerable _
        Where isValidProduct(prod) _
        Select prod
End Sub
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;
}

See Also

Other Resources

Query Examples (LINQ to SQL)