Reputation: 919
I have got a IncidentImageModel class and keeps a record of any injury parts. Either 1 or Zero. I could use Bool for true or false but somehow it is like that.
I want to loop through each property and if property value is 1, i would like to add property name to string.
For example Head = 1, Left Hand=1 and Right Feet = 1. But rest of the body parts values are 0.
how can i get list of body parts is 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;
}
I know i can do if() for each body part but i am sure there is a better way to do it. If anyone knows how to do it.
I tried this and get all properties but couldn't get property values.
PropertyInfo[] properties =
incident.IncidentImageModels.GetType().GetProperties();
for(int i=0; i<properties.count();i++)
{
properties[i].Name
}
Upvotes: 1
Views: 2330
Reputation: 5183
Here is your fixed code:
PropertyInfo[] properties = incident.GetType().GetProperties();
for (int i = 0; i < properties.Length; i++)
{
var pName = properties[i].Name;
var pValue = properties[i].GetValue(incident);
Console.WriteLine($"{pName} = {pValue}");
}
Upvotes: 2
Reputation: 277
You can use the GetValue method in combination with LINQ if you only want the properties and values with value 1:
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;
Upvotes: 2