I want to use LINQ-to-objects to query a collection of objects several levels deep, to extract a value. For example, given an Entity object I want to get the emailAddress string if a flag is set to 1, otherwise null:
Entity.CommunicationCollection.Communication.CommunicationDetail.EmailAddress
Where CommunicationDetail looks like this:
public class CommunicationDetail
{
public int Flag;
public string EmailAddress;
}
The query I came up with looks like this:
string email = Entity.CommunicationCollection.FirstOrDefault(x => x.Communication.CommunicationDetail.Flag == 1).EmailAddress;
The problem with this is that any null objects in the hierarchy will cause a null ref exception. Is there a way to structure the query to somehow ignore the nulls, without first checking every object? (The above is a simplified example, the nesting in the project I’m working on is much deeper.)
Well, you either have to check everything or use
??for defaulting, which would still be awkward. I suspect you want something like:Note that
emailcan still benullhere…Obviously if
x.Communicationcan never be null, orx.Communication.CommunicationDetailcan never be null, you can remove those checks – it’s not clear what can be null in your model.