In a C#
project, I want to be able to create a function that accepts an IQuereable<User>
object along with multiple lambda's expressions then converts it into a different object. However, instead of pulling all the available properties from the database, I want to pull only the properties that are provided to the function. Here is the logic that I think I need to follow
- Figure out what properties that I need to select
- Construct an IEnumerable from the IQueryable by specifying which properties that are needed.
- Iterate over every property that was selected and create the
Student
object.
In other words, if I call .ToList()
on the IQuereable<User> users
object, the query will select *
from the databse table which pull all available columns. Instead I want to select only the properties that are passed as labda expressions.
Here is my code
public IEnumerable<Student> Make(IQuereable<User> users, Expression<Func<User, dynamic>> keyProperty, params Expression<Func<User, dynamic>>[] propertiesToSelect)
{
var students = new List<Student>();
// Make a distinct list of lambda's expressions that I need to select
var props = propertiesToSelect.ToList();
props.Add(keyProperty);
props = props.Distinct().ToList();
// TO DO!!! Some how, I need to only select the properties that are in **props** array insted of pulling all available properties
var selectableUsers = users.Select(/**/).ToList();
foreach(var user in selectableUsers)
{
var student = new Student();
foreach(Expression<Func<User, object> exp in props)
{
var prop = GetPropertyInfo(user, exp)
object value = prop.GetValue(user, null);
// Set the property student property
// Do somthing with prop.Name...
// Do something with value...
}
students.Add(student);
}
return strudents;
}
Question How can I use LINQ to select only the list of Expressions