I need to call the method for each item in the list. So, I have used Where<> query as follows,
List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");
var name = list.Where(n =>
{
return CheckName(n);
});
But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.
As additional info, I am using.NET Framework 4.5.
Has anyone experienced this error? If so, is there any solution to overcome this issue?
You are understanding incorrectly the result of the
Wherecondition. As linq is deffered executed it will only enter the where condition when materialized (by aToList/FirstOrDefault/Sumand such).The
Whereis never actually materialized in your current code (It did as you experienced when usingFirstOrDefault) and as such it will never enter theCheckNamemethod. Then, asWherewill never returnnullbut "worst case" an empty collection, which is notnull, the result istrue.If you debug you will see that
nameequalstrueat the end of this. To "overcome" this depends on what is your desired output:If you want to know if you have any item that matched the predicate then:
If you want to retrieve those that match the predicate:
If later you want to query and check if
resultscontains anything then:If you only want the results (and thus materializing the query):
Read more about linq being deffered executed here:
Just as a side note see how you can change your current code from:
To:
And eventually to: