简体   繁体   中英

C# BsonDocument - How to check if field is an array

I receive a BsonDocument whose structure I do not know. I go through all properties, but I want to handle arrays differently. How do I find out if the field is an array?

foreach(var property in bsonDoc){
   if(/**check if its an array field**/){
     //do something
  }
}

The answer is pretty simple, I guess I was a little confused. Nevertheless, I will post a solution.

As Eldar already commented there is a bool property that says if a BsonValue is a BsonArray:

foreach(var property in bsonDoc){
   if(property.IsBsonArray){
     //do something
  }
}

Here also works the is operator: property is BsonArray

Which has the advantage that you can create a variable of the type at the same time, so I recommend this variant:

foreach(var property in bsonDoc){
   if(property is BsonArray arrayProperty){
     doSomething(arrayProperty);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM