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

1

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.
c#
linq
nullreferenceexception
asked on Stack Overflow Aug 28, 2018 by Kiran Shahi

3 Answers

7

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;
answered on Stack Overflow Aug 28, 2018 by Access Denied • edited Aug 28, 2018 by Kiran Shahi
2

You can use below code

var result = GetList().SingleOrDefault(x => x.Key == "MyKey");
if(result != null)
{
  //Add your logic
}
answered on Stack Overflow Aug 28, 2018 by Prem
1

More safe way to handle the Null in the LINQ.

GetList().Where(x => x.Key == "MyKey").Select(S=>S.MyValue).SingleOrDefault();
answered on Stack Overflow Aug 28, 2018 by Kalpesh Rajai

User contributions licensed under CC BY-SA 3.0