问题
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 NonNullPropertiesCount(object entity)
{
return entity.GetType()
.GetProperties()
.Select(x => x.GetValue(entity, null))
.Count(v => v != null);
}
(Other answers have combined the "fetch the property value" and "test the result for null". Obviously that will work - I just like to separate the two bits out a bit more. It's up to you, of course :)
回答2:
Type entityType = entity.GetType();
int count = entityType.GetProperties().Count(p => p.GetValue(p, null) != null);
回答3:
Your code is OK, can suggest using Linq
entity
.GetProperties()
.Count(x=>x.CanRead && x.GetProperty(entity, null) != null)
And don't forget to add condition, that property has getter.
来源:https://stackoverflow.com/questions/4328411/loop-through-attribute-of-a-class-and-get-a-count-of-how-many-properties-that-ar