Automapper C#Net Core-如何映射两个不同结构的列表来更改一个字段的值



我有两个列表。我需要将第一个列表(学生(中的一个字段的值更改为另一个列表(国家(中的相应值。

public class Student
{
public int Id {get;set;}
public string Name {get;set;}
public string Country {get;set;}
}
public class Countries
{
public string CountryName {get;set;}
public string CountryCode {get;set;}
}

学生名单:

[
{
"Id":1,
"Name":"John",
"Country":"Canada"
},
{
"Id":2,
"Name":"Doe",
"Country":"Japan"
},
{
"Id":3,
"Name":"Cool",
"Country":"New Zealand"
}
]

国家列表

[
{
"CountryCode":"CA",
"CountryName":"Canada"
},
{
"CountryCode":"JP",
"CountryName":"Japan"
},
{
"CountryCode":"NZ",
"CountryName":"New Zealand"
}
]

所需的JSON结果应该是:

[
{
"Id":1,
"Name":"John",
"Country":"CA"
},
{
"Id":2,
"Name":"Doe",
"Country":"JP"
},
{
"Id":3,
"Name":"Cool",
"Country":"NZ"
}
]

我可以用Automapper完成吗?Automapper是适合这个的库吗?

这似乎有些过头了。你能在studentList中循环并将国家/地区更改为countryList中的匹配项目吗?

foreach(var student in studentList)
{
student.Country = countryList.FirstOrDefault(x => x.CountryName == student.Country)
?.CountryCode
?? student.Country // some other fallback if no match found
}

您可以使用NewtonsoftJson来实现这一点。

var json = File.ReadAllText("country.json");
var countries = JsonConvert.DeserializeObject<List<Countries>>(json);

写回json

countries[0].CountryCode = "ABC"; 
json = JsonConvert.SerializeObject(countries);
File.WriteAllText("country.json", json);

最新更新