So I have an object with lots of properties, PropertyNameYear1
, PropertyNameYear2
, PropertyNameYear3
...for 20 years. these properties could potentially grow with time, so in the future I might have to add PropertyNameYear21
and so on.
I'm trying to get these properties, both their name and value, without specifying each and every one, since theoretically i can have tens of them. I can do it using LINQ and Object Initializer, but then I have to specify each property twice:
new {
PropertyNameYear1 = f => f.PropertyNameYear1,
PropertyNameYear2 = f => f.PropertyNameYear2,
...
};
How can I, using LINQ (and Refelction?), get all these properties (and only these, assuming there are other properties named differently than PropertyNameYearX
) into a new/another object and return that object?
This is a pseudo-code of what I'm looking for:
public ReturnType GetSomeObjectWithSpecificProperties(int ID){
var list = SomeObjectRepository.Where(f => f.ID == ID);
var props = list.GetType().GetProperties().ToList();
var SomePropObjectList = props.Where(f => f.Name.Contains("PropertyNameYear")).ToList();
var listToReturn = SomePropObjectList.Select(f => new {
f.Name = f.GetValue(list)
}).ToList();
return listToReturn;
}
Aucun commentaire:
Enregistrer un commentaire