Loop through attribute of a class and get a count of how many properties that are not null
问题 I was wondering if there was a simpler way to do something like this? public int NonNullPropertiesCount(object entity) { if (entity == null) throw new ArgumentNullException("A null object was 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; } 回答1: How about: public int