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