c# 4.0 - Loop through attribute of a class and get a count of how many properties that are not null -


i wondering if there simpler way this?

    public int nonnullpropertiescount(object entity)     {         if (entity == null) throw new argumentnullexception("a null object passed in");           int nonnullpropertiescount = 0;         type entitytype = entity.gettype();          foreach (var property in entitytype.getproperties())         {             if (property.getvalue(entity, null) != null)                 nonnullpropertiescount = nonnullpropertiescount+ 1;         }           return nonnullpropertiescount;     } 

how about:

public int nonnullpropertiescount(object entity) {     return entity.gettype()                  .getproperties()                  .select(x => x.getvalue(entity, null))                  .count(v => v != null); } 

(other answers have combined "fetch property value" , "test result null". work - separate 2 bits out bit more. it's you, of course :)


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -