I am trying to find whether a collection of type IEnumerable
contains a property or not.
Assuming RowModels
is a collection of type IEnumerable
, I have ...
foreach (var items in RowModels) {
if (items.GetType()
.GetProperties()
.Contains(items.GetType().GetProperty("TRId").Name) )
{
// do something...
}
}
I get the error
System.Reflection.PropertyInfo[] does not contain a definition for 'Contains'
and the best extension method overload has some invalid arguments.
You can use Enumerable.Any()
:
foreach (var items in RowModels) {
if(items.GetType().GetProperties().Any(prop => prop.Name == "TRId") )
{
// do something...
}
}
That being said, you can also just check for the property directly:
foreach (var items in RowModels) {
if(items.GetType().GetProperty("TRId") != null)
{
// do something...
}
}
Also - if you're looking for items in RowModels
that implement a specific interface or are of some specific class, you can just write:
foreach (var items in RowModels.OfType<YourType>())
{
// do something
}
The OfType<T>()
method will automatically filter to just the types that are of the specified type. This has the advantage of giving you strongly typed variables, as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With