Check property inside IEnumerable type collection

I am trying to find if a collection of type has an IEnumerable property or not.

Assuming RowModels is a collection of type IEnumerable , I ...

  foreach (var items in RowModels) { if (items.GetType() .GetProperties() .Contains(items.GetType().GetProperty("TRId").Name) ) { // do something... } } 

I get an error

 System.Reflection.PropertyInfo[] does not contain a definition for 'Contains' and the best extension method overload has some invalid arguments. 
+4
source share
2 answers

You can use Enumerable.Any() :

 foreach (var items in RowModels) { if(items.GetType().GetProperties().Any(prop => prop.Name == "TRId") ) { // do something... } } 

With this, you can also just check the property directly:

 foreach (var items in RowModels) { if(items.GetType().GetProperty("TRId") != null) { // do something... } } 

Also, if you are looking for elements in RowModels that implement a specific interface or have a specific class, you can simply write:

 foreach (var items in RowModels.OfType<YourType>()) { // do something } 

The OfType<T>() method will automatically filter only types that have the specified type. This has the advantage that you also typed variables strongly.

+7
source

Change your if to:

 if(items.GetType().GetProperty("TRId") != null) //yeah, there is a TRId property else //nope! 
+2
source

All Articles