简体   繁体   中英

Automapper C# Net Core - How can I map two lists of different structure to change the value of one field?

I have 2 lists. I need to change the value of one field from the first list(Student) with its corresponding value from the other list(Countries).

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;}
}

Student List:

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

Countries List

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

The desired JSON result should be:

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

Can I do this with Automapper? Is Automapper the right library for this?

That seems overkill. Can you just loop through the studentList and change the country to the matching item in 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
}

You can use NewtonsoftJson to achieve this.

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

write back to json

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM