Click here to Skip to main content
16,019,087 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Option 1 :

C#
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);
}


Option 2 :

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


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?
Posted
Updated 17-May-15 4:27am
v2

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.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 17-May-15 10:08am    
5ed.
—SA
Sascha Lefèvre 17-May-15 10:44am    
Thank you, Sergey.
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
C#
var result = list.Where(x => x > 5);
foreach (var item in result)
{
   Console.WriteLine(item);
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 17-May-15 10:08am    
5ed.
—SA
DamithSL 17-May-15 10:18am    
Thank You SA,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900