我对此有点陌生。好奇以下情况会发生什么?
var q = //MY LINQ TO SQL QUERY.Select(...)
.........
.........
var c = q.Count();
.........
.........
var x = q.Where(....).Select(....);
var y = x.ToList();//or something such that forces materialization
var d = q.Count();//same as c
var e = x.Count();
var f = y.Count();
sql 语句实际访问数据库多少次?一次在 Count()。再次在哪里()?还是 Linq 保留了它在 Count() 期间实现的内容?
或者它也取决于 Where(..) 有什么?就像它再次引用数据库与它只是引用作为'q'/或任何其他.net集合等的一部分获得的内容一样?
编辑:
用其他几个场景更新了我的代码。请在下面更正我的答案:
q -no db trip
c -yes, but translates to aggregate qry - select Count(*) and not a result set (as per answer below)
x -no db trip. No matter what is written in the Where(..)
y - yes
d - yes - does not *reuse* c
e - yes - select count(*) EVEN THOUGH x already materized during y
f - no db trip