我希望我的API应该返回如下数据:
"value": [{
"Name": "Name1",
"countries": ["1st Country", "2nd Country", "3rd Country"],
"Address": "Address1"
}, {
"Name": "Name2",
"countries": ["3st Country", "4nd Country", "6rd Country"],
"Address": "Address2"
}]
当我使用list时,它返回如下:
"countries": [
{ "Country": "3st Country" },
{ "Country": "4st Country" },
{ "Country": "6st Country" }
]
但我想要:
"countries": ["3st Country", "4nd Country", "6rd Country"],
请你分享一些样本编码来实现它
答案 0 :(得分:0)
My Coding is like
public List<CompanyDto> GetCompanyData()
{
List<CompanyDto> resultCompanyDtoViews = new List<CompanyDto>();
var viewCompanyDtoData = db.ds_CompanyDto.AsQueryable().AsNoTracking().ToList();
var companyDtoData = viewCompanyDtoData .Select(a => new CompanyDto()
{
Id = a.Id,
CompanyId=a.CompanyId,
CompanyName=a.CompanyName,
}).GroupBy(a => a.CompanyId).Select(a => a.First()).ToList();
foreach (var companyData in companyDtoData)
{
CompanyDto companyDto = new CompanyDto();
companyDto.Id = companyData.Id;
companyDto.CompanyId=companyData.CompanyId;
companyDto=companyData.CompanyName
companyDto.countries =
viewCompanyDtoData.Where(a => a.CompanyId == companyData.CompanyId).Select(a => new CountryDto()
{
Country = a.Country
}).ToList();
resultCompanyDtoViews.Add(companyDto);
}
return resultCompanyDtoViews;
}
-----------------------------------Coding in DTO class
public class CompanyDto
{
[Key]
public Nullable<long> Id { get; set; }
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public List<CountryDto> countries { get; set; }
}
public class CountryDto
{
public string Country { get; set; }
}
----------------------Out put Now getting
{
"value": [
{
"Id": 1,
"CompanyId": 1,
"CompanyName": "TCS",
"countries": [
{
"Country": "3st Country"
},
{
"Country": "4st Country"
},
{
"Country": "6st Country"
}
]
}
]
}
--------------------------Expected Output
{
"value": [
{
"Id": 1,
"CompanyId": 1,
"CompanyName": "TCS",
"countries": [
"3st Country",
"4st Country",
"6st Country"
]
}
]
}
Please help me out on this