如果你联合两个查询,我们是否需要先在每个查询上运行ToList()?

时间:2016-01-08 20:11:59

标签: c# .net linq

我有一些LINQ to SQL个问题,想要获得union的结果。我是否需要先对每个人运行ToList()?或者我可以将它们留作IQueryable并将它们联合起来并在工会结束时只调用一个ToList()?这有没有任何性能提升?或者它基本上是一回事?

var query1 = ( from a in this.Context.Blah select a); // .ToList()??
var query2 = ( from b in this.Context.Yada select b); // .ToList()??
var query3 = (query1.Union(query2)).ToList();

2 个答案:

答案 0 :(得分:4)

情景1:

var query1 = ( from a in this.Context.Blah select a); // you have a query
var query2 = ( from b in this.Context.Yada select b); // you have another query
var query3 = (query1.Union(query2)); // you build a new query
var result = query3.ToList(); // you execute a query and get result

情景2:

//this builds a query and execute it and get result from database
var query1 = ( from a in this.Context.Blah select a).ToList(); // you execute a query

//this builds a query and execute it and get result from database
var query2 = ( from b in this.Context.Yada select b).ToList(); // you execute another query

//this builds a query and execute it but it does not hit database because you are working
//with IEnumerable here not IQueryable
var query3 = (query1.Union(query2)); // you build a new query
var result = query3.ToList(); // you execute another query and get result

场景2执行3次查询并且有2次往返数据库,而第一次只是通过一次往返获取你想要的内容。

构建查询和执行查询之间存在很多差异。调用ToListToArrayFirstSingle和...之类的方法将执行您自调用Where,{{1}等方法后构建的查询},Union和...正在为您构建查询。

答案 1 :(得分:1)

您应该让数据库联合数据集。它可能比你能做得更快,并且任何被删除的项目都是不需要通过网络发送给你的项目。