Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambdaexpression of Linq-query in a variable

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

like image 889
Tobias Avatar asked Dec 09 '25 20:12

Tobias


2 Answers

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>.

like image 90
k.m Avatar answered Dec 11 '25 08:12

k.m


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; }
  }
like image 29
Shimmy Weitzhandler Avatar answered Dec 11 '25 10:12

Shimmy Weitzhandler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!