Reputation: 10789
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.
Upvotes: 4
Views: 2203
Reputation: 7692
Change your if
to:
if(items.GetType().GetProperty("TRId") != null)
//yeah, there is a TRId property
else
//nope!
Upvotes: 2
Reputation: 564413
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.
Upvotes: 7