[英]Iterate through properties in a loop
I'm trying to loop through a row of data for a set amount of times to access a different property every time. 我正在尝试遍历一行数据一段时间,以每次访问不同的属性。
The data looks like this: 数据如下所示:
[JsonProperty("Afbeelding")]
public string Afbeelding { get; set; }
[JsonProperty("Afbeelding_2")]
public string Afbeelding2 { get; set; }
[JsonProperty("Afbeelding_3")]
public string Afbeelding3 { get; set; }
[JsonProperty("Afbeelding_4")]
public string Afbeelding4 { get; set; }
[JsonProperty("Afbeelding_5")]
public string Afbeelding5 { get; set; }
[JsonProperty("Afbeelding_6")]
public string Afbeelding6 { get; set; }
[JsonProperty("Afbeelding_7")]
public string Afbeelding7 { get; set; }
I've tried the folllowing in the loop: 我已经尝试了以下循环:
var path = CreateFile(profitImageRow.("Afbeelding"+i), profitImageRow.Bestandsnaam+i);
The first one does not compile while the second one only adds i to the value of "Bestandsnaam" 第一个不编译,而第二个仅将i加到“ Bestandsnaam”的值上
Is there any way to make this work in a loop? 有什么办法可以使此工作循环进行吗?
First of all, it would seem that your JSON should've been deserialized as Dictionary<string, string>
, and then the Key
would be your _X properties and values would also be there. 首先,似乎您的JSON应该反序列化为Dictionary<string, string>
,然后Key
将是您的_X属性,并且值也将存在。
If you can't (or won't) change the model, you can use the powers of reflection. 如果您无法(或不会)更改模型,则可以使用反射的力量。
Eg 例如
var props = typeof(MyModel).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.Name.StartsWith("Afbeelding"));
foreach(var prop in props)
{
var value = prop.GetValue(modelHere); //now value has the corresponding string.
}
// Or you can do
for(int i =1 ; i < 8; i++){
var neededProp = props.FirstOrDefault(x => x.Name == $"Afbeelding_{i}"); //now this has the value
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.