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.
CodePudding user response:
You can't use anonymous types for this, because their properties must be declared at compile time, but you could use a dictionary:
return new JsonResult(
locations.Select(location => properties.ToDictionary(
property => property,
property => typeof(Location).GetProperty(property).GetValue(location))));
CodePudding user response:
If you know the models upfront, it would be easy to use reflection. In your case, you are generating the models on demand. Are you using ADO.net or any specific SDK? If you can iterate the database schema then it would be the best way.