Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a property inside a collection of type IEnumerable

Tags:

c#

ienumerable

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.
like image 776
BumbleBee Avatar asked Jan 14 '23 22:01

BumbleBee


1 Answers

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.

like image 174
Reed Copsey Avatar answered Jan 30 '23 20:01

Reed Copsey