How to do dynamic selection in Linq?
I am trying to figure out how to dynamically specify properties for a select clause in a linq query.
Let's say I have a collection of employee objects. At runtime, the end user will dictate what properties they would like to see for these employees, so I need to be able to dynamically build a Linq select clause.
I used the Linq dynamic library, but I prefer not to use it because I need to build a string to navigate to the select method. I would like to understand how to do this using expressions.
+2
a source to share
2 answers
Use Reflection to get dynamic column values
Column variable// has the column name as comma separated String that you can store in the DB // example string column = "Name, Id, Age";
var strColumns =columns.split(,);
foreach(var myObject in MyObjectcollection)
{
for(int index =0;index<strColumns.count();index++)
{
//Create a collection of objects
mycollection.add(myObject.GetType().GetProperty(strColumns[index]).GetValue(myObject, null));
}
}
0
a source to share