You are understanding incorrectly the result of the Where
condition. As linq is deffered executed it will only enter the where condition when materialized (by a ToList
/FirstOrDefault
/Sum
and such).
The Where
is never actually materialized in your current code (It did as you experienced when using FirstOrDefault
) and as such it will never enter the CheckName
method. Then, as Where
will never return null
but "worst case" an empty collection, which is not null
, the result is true
.
If you debug you will see that name
equals true
at 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:
var result = list.Any(CheckName);
If you want to retrieve those that match the predicate:
var result = list.Where(CheckName);
If later you want to query and check if results
contains anything then:
if(result.Any()) { /* ... */ }
If you only want the results (and thus materializing the query):
list.Where(CheckName).ToList();
Read more about linq being deffered executed here:
Just as a side note see how you can change your current code from:
var name = list.Where(n =>
{
return CheckName(n);
})
To:
var name = list.Where(n => CheckName(n));
And eventually to:
var name = list.Where(CheckName);