I have a simple API which returns a list of rows from the database like this:
[HttpGet]
[Route("list/{count}")]
public async Task<ActionResult<IEnumerable<IResult>>> GetRows(int count)
{
var list = await dbc.GetList(count);
return new JsonResult( list.ToList<IResult>() );
}
The database returns a row with attributes id, name, status etc. whereas the interface has a subset like this:
public class Result
{
int id { get; set; }
string name { get; set; }
int status { get; set; }
}
public interface IResult
{
int id { get; set; }
string name { get; set; }
}
I have the .ToList()
to return only the fields in the json result, is there a better/more efficient way than to convert to another List()
first ?
6
There’s a more optimal approach that eliminates the need to convert the list to another list with .ToList(). You can return the data as is, and during serialization, only the properties defined in the IResult interface will be included in the JSON response. Here’s how you can achieve that:
[HttpGet]
[Route("list/{count}")]
public async Task<ActionResult<IEnumerable<IResult>>> GetRows(int count)
{
var list = await dbc.GetList(count);
return new JsonResult(list);
}
When you return the list, it will still contain all the fields from the database. However, during serialization, only the properties specified in the IResult interface (id and name) will be included in the JSON response. This is because the JsonResult object only serializes those defined properties.
Returning the list directly eliminates the need for an unnecessary conversion to a new IResult list. This avoids the overhead of creating a new collection, which can improve performance, particularly with large datasets.
Ahemad Ali Khan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1