简体   繁体   中英

Check for a property inside a collection of type 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.

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.

Change your if to:

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

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