我有一些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();
Hamid Pourja.. 5
方案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次往返数据库,而第一个则只需一次往返就可以获取您想要的内容。
建立查询和执行查询之间有很多差异。调用方法,如ToList
,ToArray
,First
,Single
和......将执行,因为调用类似的方法你已经建立了查询Where
,Union
,Except
和...只是建立你的查询。
方案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次往返数据库,而第一个则只需一次往返就可以获取您想要的内容。
建立查询和执行查询之间有很多差异。调用方法,如ToList
,ToArray
,First
,Single
和......将执行,因为调用类似的方法你已经建立了查询Where
,Union
,Except
和...只是建立你的查询。