0

在 MVC4 中,我试图将模型的所有元素添加到数组中,以便获取所有非空值的计数。

例如:型号

public bool? Intubated_1 {get; set; }
public bool? Intubated_2 {get; set; }
public bool? Intubated_3 {get; set; }
public bool? Intubated_4 {get; set; }
public bool? Intubated_5 {get; set; }
public bool? some other fields

ETC...

有没有办法将所有 Intubated_x 值放入数组中以获取所有非空值的计数,或者我是否必须将所有 32 个值放入语句中并单独检查并添加到数组中?

编辑: 非常感谢所有的解决方案。我拿了一些碎片并进行了一些修改以适合我正在寻找的东西。我还有其他布尔值,所以我可以遍历所有布尔值,所以关键是建议的 .Name.StartsWith 。

List<bool?> intubatedList = new List<bool?>();
foreach (var p in adm.GetType().GetProperties())
{
    if (p.Name.StartsWith("Intubated") && p.GetValue(adm) != null)
       intubatedList.Add((bool?)p.GetValue(adm));
}
if (intubatedList.Count == adm.LOS)
    return true;
4

3 回答 3

2

看一下这个:

    public bool? Intubated_1 {get; set; }
    public bool? Intubated_2 {get; set; }
    public bool? Intubated_3 {get; set; }
    public bool? Intubated_4 {get; set; }
    public bool? Intubated_5 {get; set; }

    public List<bool?> NullableBoolPropertiesList()
    {
        List<bool?> properties = new List<bool?>();

        Type type = this.GetType();

        foreach (System.Reflection.PropertyInfo property in type.GetProperties())
        {
            if (property.PropertyType == typeof(bool?))
            {
                bool? value = property.GetValue(this) as bool?;

                properties.Add(value);
            }
        }

        return properties;
    }

用法:

        List<bool?> nullableBools = yourObject.NullableBoolPropertiesList();

        int howManyAreSet = nullableBools.Where(x => x.HasValue).Count();
        int howManyAreTrue = nullableBools.Where(x => x.HasValue && x.Value).Count();
于 2013-05-29T19:08:08.077 回答
1

做到这一点的唯一方法是通过反思。使用以下函数枚举所有属性,获取它们的值并将它们添加到列表中:

List<bool?> myList = new List<bool?>();
foreach (var p in obj.GetType().GetProperties())
{
    mylist.Add((bool?)p.GetValue(obj, null));
}

当然,如果您的类中有其他属性,则在将其添加到数组之前,您需要检查它是否是您要检查的属性之一(例如p.Name.StartsWith("Intubated")

于 2013-05-29T19:03:37.993 回答
1

也许尝试一些更光滑的东西:

private readonly bool?[] _boolArray = new bool?[5];

// Your properties
public bool? Intubated_1
{
    get
    {
        return _boolArray[0];
    }
    set
    {
        _boolArray[0] = value;
    }
}

public bool? Intubated_2
{
    get
    {
        return _boolArray[1];
    }
    set
    {
        _boolArray[1] = value;
    }
}


// Count
public int CountNonNull
{
    get
    {
        return _boolArray.Count(i => i != null);
    }
}
于 2013-05-29T19:37:25.373 回答