ToList()查询之前的代码差异

0 c# comparison performance standards entity-framework

这种方法有什么区别

public List<CollegeAddress> GetAllAddress()
{
    return collegeAppContext.CollegeAddresses.ToList().Where(x => x.StateId == 4);
}
Run Code Online (Sandbox Code Playgroud)

public List<CollegeAddress> GetAllAddress()
{
    return collegeAppContext.CollegeAddresses.Where(x => x.StateId == 4).ToList();
}  
Run Code Online (Sandbox Code Playgroud)

哪一种方法是标准代码?(但我的第一种方法扔了交谈错误:)

有什么区别?

Bil*_*ill 5

在您的第一个示例中,您将从数据库中带来所有CollegeAddresses,然后进行过滤.

您的第二个示例where为您的查询添加了一个子句,因此它在您的方法之前已经过滤.

编辑:至于第一种方法中的错误,它是因为Where返回IQueryable而不是a List.所以,你必须添加ToList();你仍然应该使用第二种方法.