Reputation: 1454
I am currently fetching a list of object from the database and would like to return it in a certain way from my ASP.Net Web API with Automapper. My Object currently looks like this after fetching it from the database:
[
{
"id": 1,
"dropdown": "Country",
"value": "Germany"
},
{
"id": 2,
"dropdown": "Country",
"value": "United States"
},
{
"id": 5,
"dropdown": "Type",
"value": "Lead"
},
{
"id": 6,
"dropdown": "Type",
"value": "Account"
},
{
"id": 7,
"dropdown": "Type",
"value": "Reseller"
},
{
"id": 8,
"dropdown": "Type",
"value": "Distributor"
}
]
But I would like it to look like this:
[{
"Countries": [{
"id": 1,
"value": "Germany"
},
{
"id": 2,
"value": "United States"
}
]
},
{
"Type": [{
"id": 5,
"value": "Lead"
},
{
"id": 6,
"value": "Account"
}
]
}
]
Currently my CreateMap looks like this
CreateMap<DropdownValue, DropdownValueListDto>();
And my DropdownValueListDto like this
public class DropdownValueListDto
{
public int Id { get; set; }
public string Dropdown { get; set; }
public string Value { get; set; }
}
My LINQ Operation looks like this:
public async Task<IEnumerable<DropdownValue>> GetDropdownValues(string[] dropdowns)
{
var dropdownValues = _context.DropdownValues.OrderBy(x => x.Id).ThenBy(x => x.Dropdown).AsQueryable();
if (dropdowns.Length != 0 || dropdowns != null)
{
dropdownValues = dropdownValues.Where(x => dropdowns.Contains(x.Dropdown));
}
var dropdownValuesToReturn = await dropdownValues.ToListAsync();
return dropdownValuesToReturn;
}
It would be great if someone could help me achieve this.
Thanks in advance
Upvotes: 0
Views: 182
Reputation: 2626
based on your edits, I guess you'd have to do something like this:
//Your result class should actually look like this to match JSON:
class DropDownListDto
{
public string Description {get;set;}
//here you need an IEnumerable to store the list of Ids and values associated
//with this drop-down. you could create a class and declare a LIST<> of that
//but I'll just use a dictionary instead.
public Dictionary<int, string> DropDownValues{get;set;}
}
//Get source data
var source = await GetDropDownValues(<insert [] here>);
//transform list into IEnumerable<DropDownListDto>
var result = source
//if we GROUP BY the Dropdown property then we'll get a distinct list of
//of drop-downs.
.GroupBy(x=>x.DropDown)
//can then get the list of values and Ids from the resulting groups
.Select(g=>new DropDownListDto
{
//key is the grouped by thing - drop down name..
Description = g.Key,
//doing a .select from the group result gives the elements
//in that group only. Get an anonymous type and cast that
//to our required dictionary type
DropDownValues = g
.Select(x=>new{ key=x.Id, value = x.Value})
.ToDictionary(k=>k.key, v=>v.value)
});
That should give you something like what you want - I've not tested this though...
Upvotes: 1