I have a simple LinQ query in this way:
myList.Where(x=> x.Property.Property2 == 5);
However, Property could be null and then I get an error. So I would like to know if there is any way to check if it is null, if not null, do the comparation, if it is null, throw an exception.
Because if not, I have to use a foreach to check each element, in this way:
List<MyType> myLstResult = new List<MyType>();
foreach(MyType iterator in myList)
{
if(iterator.Property == null)
{
throw new ArgumentNullException();
}
if(iterator.Property.Property2 == 5)
{
myLstresult.Add(iterator);
}
}
Thanks.
Yes you can extend the lambda just like that:
myList.Where(x=>
{
if (x.Property == null)
throw new ArgumentNullException();
return x.Property.Property2 == 5;
});
This will of course only work in "normal" linq. Linq-to-sql or -entity query providers will probably not be able to translate that to sql.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With