English 中文(简体)
选择一个等级的归属,并算出有多少不作废的财产
原标题:Loop through attribute of a class and get a count of how many properties that are not null
  • 时间:2010-12-01 19:47:46
  •  标签:
  • c#-4.0

我很想知道,是否有更简单的方式来做这样的事情?

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

(其他答复将“不动产价值”和“对无效结果的检验”结合起来。) 显然,这将奏效——我只想把两点分开。 当然,这取决于你:

问题回答
Type entityType = entity.GetType();

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

你的法典是大韩民国,可以建议使用林克

entity
  .GetProperties()
  .Count(x=>x.CanRead && x.GetProperty(entity, null) != null)

而且不要忘记附加条件,这种财产已经消失。





相关问题
Howto get started with C# 4.0 and .NET 4.0?

I don t want to download Visual Studio 2010. How can I start studying (not developing real applications) C# 4.0 and .NET 4.0 with just a text editor? Can I just download C# 4.0 compiler and .NET 4.0 ...

Mocking Framework with C# 4.0 Support?

Anybody know of a mocking framework that supports C# 4.0? Doesn t matter which one ATM, just need something that will work.

Unit Testing interface contracts in C#

Using the Code Contracts tools available in VS2010 Beta 2, I have defined an interface, a contract class for that interface and two classes that implement the interface. Now when I come to test the ...

How to Iterate Through Array in C# Across Multiple Calls

We have an application where we need to de-serialize some data from one stream into multiple objects. The Data array represents a number of messages of variable length packed together. There are no ...

IronPython ScriptRuntime equivalent to CPython PYTHONPATH

The following import works inside ipy.exe prompt but fails using IronPython ScriptRuntime inside a C# 4.0 program. import ConfigParser C# code: using System; using System.Collections.Generic; using ...

i cant understand the following code

Matrix<float> trainData2 = trainData.GetRows(intVar >> 1, intVar, 1); intVar is integer type... please help me to understand this code.

热门标签