将某一类型转换为泛型 IEnumerableConvert a Type to a Generic IEnumerable

使用 AsEnumerable 可返回类型化为泛型 IEnumerable 的参数。Use AsEnumerable to return the argument typed as a generic IEnumerable.

示例Example

在此示例中,LINQ to SQLLINQ to SQL(使用默认泛型 Query)会尝试将查询转换为 SQL 并在服务器上执行。In this example, LINQ to SQLLINQ to SQL (using the default generic Query) would try to convert the query to SQL and execute it on the server. where 子句引用用户定义的客户端方法 (isValidProduct),此方法无法转换为 SQL。But the where clause references a user-defined client-side method (isValidProduct), which cannot be converted to SQL.

解决方法是指定 IEnumerable<T> 的客户端泛型 where 实现以替换泛型 IQueryable<T>The solution is to specify the client-side generic IEnumerable<T> implementation of where to replace the generic IQueryable<T>. 可通过调用 AsEnumerable 运算符来执行此操作。You do this by invoking the AsEnumerable 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;
}
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

请参阅See also