【发布时间】:2015-10-30 04:25:30
【问题描述】:
我经常看到调用 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 的真正作用。我没有以这种方式实现它。 另外,我进行了一个存储过程调用以从 db 返回客户,并从返回的数据表中创建一个客户列表。
【问题讨论】:
-
为什么要这样做?而是在调用 ToList() 后存储列表并使用它?
-
请检查我的编辑。
-
你是对 List() 做再次列表还是在 IQueryable 上?
-
它是 LINQ 查询 (
IQueryable) 而不是一个集合 (IEnumerable),它可能会被多次评估(可能会对性能造成重大影响),如果如果您不执行.ToList(),则在您的代码中多次引用。这可能取决于 LINQ 提供程序。