+ 2
How to handle empty search results in linq
I like to query an list using linq. It is possible that there are no valid results to the query. At this moment I get an nullrefenceexception, which I do not want. What is the best way to solve this ? https://code.sololearn.com/ctNG0MKEZ0TK/?ref=app
3 ответов
+ 1
It does not return null. lambda expression returns an Enumerator.
You can use Count there as
if(animals.Where(a => a.StartsWith("a")).Count() != 0 ) {
Console.WriteLine("animal with a");
}
else
{
Console.WriteLine("No animal with a");
}
if Count not equal to 0, then you can use a loop inside if.
+ 1
Your Lamda expression does not return null.
You can try this way :
foreach(var a in animals)
if(a.StartsWith("a"))
Console.WriteLine("animal with a");
else
Console.WriteLine("No animal with a");
else :
var result = (from a in animals where a.StartsWith("a") select a).ToList();
foreach(var i in result)
Console.WriteLine(i + " animal with a");
+ 1
I understand I can do it that way. But this is just example code.
I like to use linq and a if statement to determine whether there are any results or no results.