ToList vs foreach查询执行 [英] ToList vs foreach query execution

查看:121
本文介绍了ToList vs foreach查询执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选项1:



Option 1 :

List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
var result = list.Where(x => x > 5).Select(x => x);
foreach (var item in result)
{
   Console.WriteLine(item);
}





选项2:





Option 2 :

list = list.Where(x => x > 5).Select(x=> x).ToList();
if(list != null && list.Count> 0)
{
     foreach (var item in list)
     {
          Console.WriteLine(item);
     }
}





选项1仅在需要时执行查询但我不确定它是否处理每次if IEnumerable都不包含任何值时,null引用异常。



选项2立即执行查询并处理空检查和计数检查。



哪个选项更好?



Option 1 executes query only when it is needed but I am not sure whether it handles null reference exception every time if given IEnumerable does not contain any value.

Option 2 executes query immediately and handles null check and count check.

Which option is better?

推荐答案

选项1:

如果IEnumerable没有元素, foreach循环不会执行。除非您在讨论结果可能为空(它不能在您的具体示例代码中),否则不存在空引用异常的风险。如果它可以为null,你必须先检查它。



选项2:

你可能打算在那里写: foreach(列表中的var项目)

list 不能在具体的代码示例中为null,因此在此处不需要检查null。检查list.Count> 0是否也是必要的,因为如果它是0那么foreach-loop就不会执行。



哪一个更好?

如上所述,检查null和.Count = 0在选项2中没有多大意义。

剩下的区别在于是否使用延迟执行(通过使用ToList())。答案就是:这取决于可能有​​一些因素。以下两个因素可能是最重要的因素:如果需要多次迭代元素,那么使用ToList()而不是延迟执行可能会更高效。如果您事先不知道是否要将元素枚举到最后,那么延迟执行可以更高效。
Option 1:
In case the IEnumerable has no elements, the foreach-loop won't execute. There's no risk of a null-reference exception unless you're talking about result potentially being null (which it can't be in your concrete sample code). You would have to check for that before if it could be null.

Option 2:
You probably meant to write there: foreach (var item in list)
list can't be null in your concrete code sample, so checking for null isn't neccessary here. Checking if list.Count>0 also ins't neccessary because if it would be 0 then the foreach-loop simply wouldn't execute.

Which one is better?
As explained, the check for null and for .Count=0 doesn't make much sense here in option 2.
The remaining difference is in using deferred execution or not (by using ToList()). And the answer to this is: It depends and there can be a few factors. Here are the two factors which are probably the most important ones: If you need to iterate over the elements multiple times then it can be more performant to use something like ToList() instead of deferred execution. If you don't know beforehand if you will enumerate the elements to the end, then deferred execution can be more performant.


如果没有匹配,则返回空序列;什么是更好的!我会删除无意义的。选择(x => x)并直接使用foreach而不进行空检查或计数检查

Where returns an empty sequence if there are no matches; what is better! I would remove meaningless .Select(x=> x) and use foreach directly without null check or count check
var result = list.Where(x => x > 5);
foreach (var item in result)
{
   Console.WriteLine(item);
}


这篇关于ToList vs foreach查询执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆