mardi 23 juin 2015

Create a subset of an object based off an array of property names

I have a class and an array of property names defined as follows:

public class Dog {
    public string Name { get; set; }
    public string Breed { get; set; }
    public int Age { get; set; }
}

var desiredProperties = new [] {"Name", "Breed"};

I also have a method that returns a list of dog objects:

List<Dog> dogs = GetAllDogs();

Is there an way I can return a subset of dogs that only contain the properties defined within the desiredProperties array? Eventually, this resulting list will be serialized to JSON.

I have been struggling with this problem for some time now, considering that the user will be allowed to specify any combination of properties (assuming they are all valid) as the output within the array. Some more examples:

var desiredProperties = new [] {"Name", "Age"};
// Sample output, when serialized to JSON:
// [
//   { Name: "Max", Age: 5 },
//   { Name: "Spot", Age: 2 }
// ]

var desiredProperties = new [] {"Breed", "Age"};
// [
//   { Breed: "Scottish Terrier", Age: 5 },
//   { Breed: "Cairn Terrier", Age: 2 }
// ]





Aucun commentaire:

Enregistrer un commentaire