I having a hierarchy collection object where I am trying to retrieve the last level object’s property in Linq. I dont want to write a get method for every property. Not sure how to achieve it through selector
Class Test {
public int ID { get; set; }
public int PopertyA { get; set; }
public string PopertyB { get; set; }
...Many more properties
}
public static TResult GetTest(hierarchyObject, int ID, Func<TSource, TResult> selector)
{
return (from level1 in hierarchyObject.Level1
from test in level1.Test
where test.ID.Equals(ID)
select selector).First();
}
This dint work. Currently I have made the method to return the test object and accessing the properties in the calling method. But wanted to know if I can implement a generic property getter.
Edit:
Class Hierarcy{
public IList<Level1> level1;
}
Class Level1 {
public IList<Test> test;
}
Given a hierachy object and test.ID, I want to retrieve any property of Test.
It depends on what you want to do with your property. To avoid repeating the entire LINQ query for each and every property you are interested in, it would be better to get the Test object first, and then check its individual properties:
Once you get the
Testclass, you have all its properties:If you are interested in getting a value of a property dynamically, using its name only, you can do it using Reflection:
In both examples, actual query is executed only once, which can be significant if there are lots of objects in your collections.