当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如果您合并两个查询,我们是否需要首先在每个查询上运行ToList()?》经验,为你挑选了1个好方法。

我有一些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次往返数据库,而第一个则只需一次往返就可以获取您想要的内容。

建立查询和执行查询之间有很多差异。调用方法,如ToListToArrayFirstSingle和......将执行,因为调用类似的方法你已经建立了查询WhereUnionExcept和...只是建立你的查询。



1> Hamid Pourja..:

方案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和......将执行,因为调用类似的方法你已经建立了查询WhereUnionExcept和...只是建立你的查询。

推荐阅读
携手相约幸福
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有