I am trying to create a csv exporter that exports models from our database to a CSV file. As a requirement, for each export, the user is able to select what properties of the model need to be exported.
Is it possible to return an anonymous type with just the selected properties, where the properties are chosen by the user and thus not known
Example Data class:
public class Location
{
public Location() { }
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Manual example:
public IActionResult GetSelectProperties()
{
var locations = new List<Location>(); // Assume a filled list
return new JsonResult(locations.Select(x => new {x.Name, x.City}));
}
The ideal (incomplete) solution
public IActionResult GetSelectProperties2()
{
var locations = new List<Location>();
var properties = new List<string>() { "Name", "City" };
return new JsonResult(locations.Select(x => { < where x in properties ?> }));
}
I have tried using reflection
var property = typeof(Location).GetProperty("Name");
but don't know how to combine the PropertyInfo in the LINQ query.
Aucun commentaire:
Enregistrer un commentaire