我经常看到调用ToList会导致查询每次执行。对此我有些困惑。在这种情况下,第二次调用ToList会使查询执行超过一次吗?在什么情况下查询会执行多次?
//This gets from database and ToList is already called here
List<Customer> Customers = GetCustomersFromDataBase();
//ToList is called here again
List<Customer> FilteredCustomers = (from c in Customerswhere c.id == 1c).ToList();
编辑
我提供了这个代码示例,以便更好地理解ToList的作用。但我并不是按照这种方式实现它。 此外,我调用了一个存储过程来从数据库中返回客户信息,并从返回的数据表创建了一个客户列表。
IQueryable
),而不执行.ToList()
,则可能会对性能产生潜在和显著的影响。这取决于LINQ提供程序。因此,应该使用LINQ查询而不是集合(IEnumerable
)。 - user585968