How can I define a lambdaexpression that I want to use in a linq query as a variable?
For example when sorting a generic list by different properties of the listitems:
IList<SampleClass> list = new List<SampleClass>();
// Populate list
...
list.OrderBy(sampleclass => sampleclass.property1);
list.OrderBy(sampleclass => sampleclass.property2);
I would like to define the lambda expression (sampleclass => sampleclass.property1) in a variable and call:
// ??? define expression in a variable ???
Expression expression = sampleclass => sampleclass.property1;
// Sort list by variable expression
list.OrderBy(expression);
Thanks in advance Tobi
You can use one of Func overloads (Func<T, TResult> precisely):
Func<SampleClass, PropertyType> expr = sampleclass => sampleclass.property1;
list.OrderBy(expr);
PropertyType is the type of variable stored as property1 in your SampleClass. If it was for example string, you would use Func<SampleClass, string>.
Define a Func<TSampleClass, TPropertyType> as follows:
List<SampleClass> list = new List<SampleClass>();
Func<SampleClass, int> expr = (c) => c.SomeProperty;
_HungerLevel = level;
class SampleClass
{
public int SomeProperty { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With