我想知道是否有更简单的方法来做这样的事情?
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;
}
Run Code Online (Sandbox Code Playgroud)
怎么样:
public int NonNullPropertiesCount(object entity)
{
return entity.GetType()
.GetProperties()
.Select(x => x.GetValue(entity, null))
.Count(v => v != null);
}
Run Code Online (Sandbox Code Playgroud)
(其他答案结合了"获取属性值"和"测试结果为空".显然这将起作用 - 我只想将两个位分开一点.这取决于你,当然:)
归档时间: |
|
查看次数: |
4533 次 |
最近记录: |