有这样一个案例:
var filteredResult = from f in orgFileList select f; for (int i = 0; i < WorkStatusFilters.ListWorkStatus.Count; i++) { if( !WorkStatusFilters.ListWorkStatus[i].checkStatus) filteredResult = filteredResult.Where(f => f.WorkStatusFlag != i.ToString()); }
这段代码的本意是筛选掉指定workstatusFlag的数据,但由于延迟执行的机制,使得该linq查询结果至少在for循环结束后才真正的执行,而这个时候i作为局部变量已经取不到值了。本应该是如下的查询:
filteredResult = filteredResult.Where(f => f.WorkStatusFlag != "0").Where(f => f.WorkStatusFlag != "2").Where(f => f.WorkStatusFlag != "5");
实际结果却是:
filteredResult = filteredResult.Where(f => f.WorkStatusFlag != null ).Where(f => f.WorkStatusFlag != null).Where(f => f.WorkStatusFlag != null);
从而导致莫名的数据异常。
此处我的修正建议是:显示调用 toList:
var filteredResult = from f in orgFileList select f; for (int i = 0; i < WorkStatusFilters.ListWorkStatus.Count; i++) { if( !WorkStatusFilters.ListWorkStatus[i].checkStatus) filteredResult = filteredResult.Where(f => f.WorkStatusFlag != i.ToString()).ToList(); }
但这样做会牺牲一些性能,在大数据量时体现比较明显。