变量中 Linq 查询的 Lambda 表达式
如何定义要在 linq 查询中用作变量的 lambda 表达式?
例如,当按列表项的不同属性对通用列表进行排序时:
IList<SampleClass> list = new List<SampleClass>();
// Populate list
...
list.OrderBy(sampleclass => sampleclass.property1);
list.OrderBy(sampleclass => sampleclass.property2);
我想在变量中定义 lambda 表达式 (sampleclass => Sampleclass.property1) 并调用:
// ??? define expression in a variable ???
Expression expression = sampleclass => sampleclass.property1;
// Sort list by variable expression
list.OrderBy(expression);
提前致谢 飞鸟
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用
Func
重载之一 (Func< ;T, TResult>
准确地说):PropertyType
是存储为property1
的变量类型示例类
。例如,如果是string
,您将使用Func
。You can use one of
Func
overloads (Func<T, TResult>
precisely):PropertyType
is the type of variable stored asproperty1
in yourSampleClass
. If it was for examplestring
, you would useFunc<SampleClass, string>
.定义
Func
如下:Define a
Func<TSampleClass, TPropertyType>
as follows:您可以使用:
这假定 Property1 的类型是 int。
You can use:
This presumes the type of Property1 is int.
你几乎已经做到了。
参数是从序列中获取项目并给出其键作为结果的任何函数(将在其上完成排序的键)。 lambda 表达式只是此类函数的变体。
这些符号是可能的:
或
或
(我在这里假设
property1
是一个字符串,但这当然不是必需的!)You have almost already done it.
The parameter is any function taking an item from the sequence and giving its key as a result (the key on which the ordering will be done). A lambda expression is just a variety of such a function.
These notations are possible :
or
or
(I supposed here that
property1
was a string but it's of course not a requirement !)就像其他人所说的那样,您可以使用
Func
来存储函数的委托。如果您想使用 Linq-To-Objects 之外的其他内容,那么您也应该将其包含在表达式中。类似于
Expression>
。Just like other people said, you can use
Func<T, TResult>
to store delegate to your function.If you want to use something else than Linq-To-Objects, then you should enclose this in Expression too. Something like
Expression<Func<T, TResult>>
.如果您纯粹讨论 LINQ to Objects,则此处不需要
Expression
,因为Enumerable.OrderBy
的参数是Func
委托:如果你想多次赋值,你可以让
Func
返回object
:如果你确实想要动态属性选择,即调用
OrderBy
指定了属性通过字符串
,您将需要表达式
。 此线程中有很多示例,允许您执行以下操作:If you are talking purely about LINQ to Objects, there's no need for
Expression
s here because the argument toEnumerable.OrderBy
is aFunc
delegate:If you want to assign multiple times, you can make
Func
returnobject
:If you truly want dynamic property selection, i.e. calling
OrderBy
with a property specified by astring
, you would needExpression
s. There are plenty of examples in this thread that allow you to do something like: