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

匆匆过客 提交于 2021-02-19 08:03:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!