开发者

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;
    }


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 :)


Type entityType = entity.GetType();

int count = entityType.GetProperties().Count(p => p.GetValue(p, null) != null);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜