本文介绍了在一个可变的LINQ查询Lambdaexpression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何定义,我想在LINQ查询中使用的变量的lambdaexpression?

How can I define a lambdaexpression that I want to use in a linq query as a variable?

例如排序由listItems中的不同属性的通用列表时

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);



我想在一个变量和呼叫来定义lambda表达式(sampleclass => sampleclass.property1)

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 advanceTobi

推荐答案

您可以使用 Func键之一重载(的准确):

You can use one of Func overloads (Func<T, TResult> precisely):

Func<SampleClass, PropertyType> expr = sampleclass => sampleclass.property1;
list.OrderBy(expr);



属性类型存储为变量的类型 property1 SampleClass 。如果是例如字符串,你可以使用 Func键< SampleClass,串方式>

PropertyType is the type of variable stored as property1 in your SampleClass. If it was for example string, you would use Func<SampleClass, string>.

这篇关于在一个可变的LINQ查询Lambdaexpression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 20:05