Home > Back-end >  How to map a list in response to a different list in a variable
How to map a list in response to a different list in a variable

Time:08-30

I am trying to map the Id and name in SearchCompanyResponse to the variable companies that is a list of Company.

 var searchCompany = new SearchCompanyRequest();
 searchCompany.Query = request.Name;
 searchCompany.DatlinqKey = "TestKey";
 var searchCompanyResponse = GetApi<SearchCompanyRequest,SearchCompanyResponse>(DatlinqApiMethod.SearchCompany, searchCompany);        
 var companies = new List<Company>();

This is the SearchCompanyResponse

public class SearchCompanyResponse
{
    public List<SearchCompanyResponseCompany> Result { get; set; }
}

public class SearchCompanyResponseCompany
{
    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

And this is the Company

public class Company
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }
    }

CodePudding user response:

You could use AutoMapper, but since this is a simple example the following should do:

var companies = searchCompanyResponse.Result
               .Select(res => new Company {Id = res.Id, Name = res.Name})
               .ToList();
  • Related