I am using .Net Framework 4, mvc 3 and entity framework (latest stable)
On an index page I want to be able to filter each column. The filter values are retrieved for each column by LINQ using the distinct() method. I have not found a good way to reuse the method that retrieves these values for each column – they are basically equal, the only thing differentiating them is the column name used, so having one method instead of several would be great.
public List<string> GetLevels()
{
return _db.Logs.Select(l => l.Level).Distinct().ToList();
}
public List<string> GetOrders()
{
return _db.Logs.Select(l => l.Order).Distinct().ToList();
}
How can I inject the lambda expression with the column name I want to retrieve data from? Something like this:
public List<string> GetFilterValues(string columName)
{
return _db.Logs.Select(l => l.columnName).Distinct.ToList();
}
You can write a function which takes an expression selecting the property you want:
EDIT: If you want to create the projection from a string column, you will have to build the expression yourself:
Note that this will throw an exception if the property with the given name is not a
stringproperty.