Take for example the following extract from a mongo collection :
{"IsBasedOnProduct" : {
"CodeUV" : "09184",
"Name" : null,
"pricingVersion" : "B"
}
}
I would like to extract the Name
field from this collection and put it in a C# object. But i do not know how to manage the null
value.
This is what I am doing in my C# application :
if (foo.Contains("IsBasedOnProduct"))
{
fooToExcel.Name = foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name") ? foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}
Of course when the Name
is null
, i throw an System.ArgumentNullException
How can I fix it in order to put string.Empty
when the value is null
?
Fix it using the following snapshot of code :
if (foo.Contains("IsBasedOnProduct") && foo["IsBasedOnProduct"].BsonType != BsonType.Null)
{
fooToExcel.Name = foo["IsBasedOnProduct"].AsBsonDocument.Contains("Name")&& foo["IsBasedOnProduct"]["Name"].BsonType != BsonType.Null ?
foo["IsBasedOnProduct"]["Name"].AsString : string.Empty;
}