Build lambda expression dynamically
I am trying to sort a object collection dynamically. Ideally I would want it to do the below functionality where I could specify the criter开发者_如何学Pythonia at runtime.
_group.OrderByDescending(rec => "rec.CalculatedRecord.GL.PropertyValue").Take(Convert.ToInt16(_filters.Value))
I tried dynamic linq which didn't work.
var query = (from enumerable in _group
orderby "rec.CalculatedRecord.GL.PropertyValue"). descending
select enumerable).Take(5);
A note on why the second one shouldn't work: your object of enumeration is called enumerable
yet in your string you are still using rec
as in the lambda earlier. changing the string to use enumerable
instead of rec
might alleviate your issues.
The OrderByDescending
method takes a parameter of Func<TSource, TKey>
. While you can insert a lambda here, as is the most common use case, you can also pass in a variable. The variable can be dynamically assigned based on whatever you logic might be.
I have had to infer your class structure, but here's a basic example:
public class Record
{
public CalculatedRecord CalculatedRecord { get; set; }
}
public class CalculatedRecord
{
public GL GL { get; set; }
}
public class GL
{
public PropertyValue PropertyValue1 { get; set; }
public PropertyValue PropertyValue2 { get; set; }
}
public class PropertyValue { }
Then you can create the following logic:
public class TestHarness
{
public void Test()
{
IEnumerable<Record> Group = new List<Record>();
//Simple flag
bool someCriteria = true;
//Define orderByFunc
Func<Record, PropertyValue> orderByFunc;
//Assign the order by function based on someCriteria
if (someCriteria)
{
orderByFunc = record =>
record.CalculatedRecord.GL.PropertyValue1;
}
else
{
orderByFunc = record =>
record.CalculatedRecord.GL.PropertyValue2;
}
//Execute OrderBy
var updated = Group.OrderByDescending(orderByFunc).Take(5);
}
}
However, this doesn't allow you to generate the Func dynamically at runtime. In order to do that you will need to build an Expression
using expression trees and then compile it. You can follow the steps at Expression.Lambda and query generation at runtime, simplest "Where" example
精彩评论