与LINQ to Entities一起使用foreach时是否需要ToList

编程入门 行业动态 更新时间:2024-10-11 15:13:42
本文介绍了与LINQ to Entities一起使用foreach时是否需要ToList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个性能问题,关于LINQ如何使用foreach在实体框架中的可查询实体上执行.

I have a performance question regarding how LINQ performs with a foreach over an queryable entities from Entity Framework.

两者做的更好(更快)

foreach(var thing in myentities.GetThemAll())

foreach(var thing in myentities.GetThemAll().ToList())

第一个示例实际上会导致myentities.GetThemAll().Count()(+1?)次到数据库的每次旅行都收集一行吗?

Will the first example actually result in myentities.GetThemAll().Count() (+1 ?) trips to the database each collecting one row?

推荐答案

如果只需要遍历元素而不调用ToList(),则更好.这是因为当我们调用它时,将触发相应查询的立即执行,并将创建一个内存中的集合.

It is better, if you have only to iterate through your elements to not call ToList(). This is because when we call it, an immediate execution of the corresponding query is triggered and one in memory collection will be created.

如果不调用ToList,则将避免创建用于保存查询结果的内存中集合.

If you don't call ToList you will avoid the creation of the in memory collection that will hold the results of your query.

无论您采用第一种方法,还是第二种方法,都将一次往返数据库.

Either you follow the first way, either the second, you will make one round trip to the database.

更多推荐

与LINQ to Entities一起使用foreach时是否需要ToList

本文发布于:2023-11-22 00:23:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615256.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Entities   LINQ   ToList   foreach

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!