Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return null when the Linq query returns empty value?

I have the following code to get values from the list.

GetList().SingleOrDefault(x => x.Key == "MyKey").MyValue;

When there is Key property with value MyKey in a list it is working fine but when there is not Key property with value MyKey in a list it is throwing an NullReferenceException. How can I return null value instead of exception.

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
like image 522
Kiran Shahi Avatar asked Feb 24 '26 08:02

Kiran Shahi


1 Answers

Use ?. and ?[] null-conditional Operators. It tests the value of the left-hand operand for null before performing a member access (?.) or index (?[]) operation; returns null if the left-hand operand evaluates to null.

GetList().SingleOrDefault(x => x.Key == "MyKey")?.MyValue;
like image 130
Access Denied Avatar answered Feb 25 '26 22:02

Access Denied



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!