c#获取所有属性值

标签 c#

我有一个 IncidentImageModel 类并记录任何受伤部位。 1 或零。我可以使用 Bool 来表示 true 或 false,但不知何故就是这样。

我想遍历每个属性,如果属性值为 1,我想将属性名称添加到字符串。

例如,头 = 1,左手 = 1,右脚 = 1。但其余 body 部位的值为 0。

我怎样才能得到 body 部位的列表是 1?

public class IncidentImageModel
{
    [Key]
    public int IncidentImageID { get; set; }
    public int IncidentID { get; set; }
    public int ClientID { get; set; }
    public int Head { get; set; } = 0;
    public int Neck { get; set; } = 0;

    public int RightShoulder { get; set; } = 0;
    public int LeftShoulder { get; set; } = 0;
    public int Chest { get; set; } = 0;

    public int RightArm { get; set; } = 0;
    public int LeftArm { get; set; } = 0;
    public int LowerAbdomin { get; set; } = 0;

    public int RightHand { get; set; } = 0;
    public int Genitals { get; set; } = 0;
    public int LeftHand { get; set; } = 0;

    public int LeftUperLeg { get; set; } = 0;
    public int RightUperLeg { get; set; } = 0;

    public int RightLowerLeg { get; set; } = 0;
    public int LeftLowerLeg { get; set; } = 0;

    public int RightFeet { get; set; } = 0;
    public int LeftFeet { get; set; } = 0;
}

我知道我可以对每个 body 部位执行 if(),但我确信有更好的方法来做到这一点。如果有人知道该怎么做。

我尝试了这个并获取了所有属性,但无法获取属性值。

 PropertyInfo[] properties = 
 incident.IncidentImageModels.GetType().GetProperties();
 for(int i=0; i<properties.count();i++)
 { 
    properties[i].Name
 }

最佳答案

如果您只需要值为 1 的属性和值,则可以将 GetValue 方法与 LINQ 结合使用:

var incidentImageModel = new IncidentImageModel();
PropertyInfo[] properties = incidentImageModel.GetType().GetProperties();

var result = from property in properties
             let nameAndValue = new { property.Name, Value = (int)property.GetValue(incidentImageModel) }
             where nameAndValue.Value == 1
             select nameAndValue;

关于c#获取所有属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57609394/

相关文章:

c# - 将空 XML 元素呈现为父元素

c# - 我如何从WhenAll(任务数组)中获取结果

c# - 从 DbContext 中检索未提交的实体

c# - 如何在 UWP 中获取已连接的扫描仪列表

c# - 通过属性设置 Treeview HierarchicalDataTemplate

c# - 我应该如何开始玩 3D?

c# - 如何在使用 EF 期间向 C# 中的类添加额外的属性

c# - WCF 身份检查失败

c# - 如何将内联 SQL 转换为 SQL Server 中的存储过程

c# - TFS REST API - 获取字段的允许值