'How do I map a list of objects to return a specific property in my ASP.NET API application?
I've made a basic Web API and I'm working on a list of games and their platforms. When I hit my API endpoint with postman, I see the following information.
[
{
Title: "God of War,
Platform: "Xbox"
},
{
Title: "Grand Theft Auto",
Platform: "Xbox"
}
]
However, I don't need to return the platform from my API, only the title. So the array should look like this when my API endpoint is hit:
[
"God of War",
"Grand Theft Auto"
]
If this was JavaScript then you could easily map this but with C# I'm not sure how. Below is my code starting with the controller:
[HttpGet]
[Route("/v1/api/games")]
public IEnumerable<Games> GetGames()
{
List<Games> games = new()
{
new Games
{
Title = "Hunted",
IsPrimary = false
},
new Games
{
Title = "Grand Theft Auto",
IsPrimary = false
}
};
//var test = games.Select(x => x.Title).ToArray(); Doesn't seem to work
return games;
}
The model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyProject
{
public class Games
{
public string Title { get; set; }
public bool? IsPrimary { get; set; }
}
}
My question is, how can I map my list to return only the titles in the way I've shown?
Solution 1:[1]
You can simply change your method signature to
IEnumerable<string> GetGames()
and return
games.Select(x => x.Title);
Or mark the Platform property on Game class with attribute [Ignore] if you want to ignore it completely in your overall application.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vendettamit |
