循环遍历一个类的属性,并获得不为null的属性的计数 [英] Loop through attribute of a class and get a count of how many properties that are not null

查看:50
本文介绍了循环遍历一个类的属性,并获得不为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;
    }

推荐答案

怎么样:

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

这篇关于循环遍历一个类的属性,并获得不为null的属性的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆