我有一个IncidentImageModel类,并记录了任何受伤部位。1或零。我可以将Bool用作是非题,但不知何故。
我想遍历每个属性,如果属性值为1,我想将属性名称添加到字符串。
例如,Head = 1,左手= 1,右脚=1。但是身体其余部位的值为0。
我如何获取身体部位的清单为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;
}
我知道我可以为每个身体部位做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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句