Greg
Greg

Reputation: 11480

Anonymous Type and Null

Our company utilizes a service, which gives developers access to their application through a Rest Api. So based on the content that this application generates, I built a data model to represent the Extensible Markup Language (XML) for easier modification.

However the API generates two separate areas for data:

var responses = submission.Sections.SelectMany(obj =>
     obj.Screens.Screen.Responses.Response.Select(response => 
     new { response.Label, response.Value, response.Type })).ToList();

var responses = submission.Sections.SelectMany(obj =>
     obj.Screens.Screen.Responses.Responses.Response.Select(response => 
     new { response.Label, response.Value, response.Type })).ToList();

As you can see when I'm building the content Responses.Response is where a bulk of the data, however sometimes it utilizes Responses.Responses.Response. Is there a way to do a preliminary projection on the data? This way I could test for the null that is occasionally thrown in Responses.Response?

That way I could do something along these lines:

if(obj != null)
{
     // Responses.Response
}
else
{
     //Responses.Responses.Response
}

Is that even possible with Linq? The problem is because response.Value is null in certain instances, it throws a Null Argument Exception.

Upvotes: 2

Views: 422

Answers (1)

brz
brz

Reputation: 6016

You can use the null-coalescing operator:

var responses = submission.Sections.SelectMany(obj =>
 (obj.Screens.Screen.Responses.Response ?? obj.Screen.Responses.Responses.Response).Select(response => 
 new { response.Label, response.Value, response.Type })).ToList();

Upvotes: 5

Related Questions