在 Func/lambda 表达式中重用方法调用
首先我要说的是,我不确定这个问题的标题是否有意义,但我不确定如何表达我的问题。
我有一个类定义为
public static class NaturalSort<T>
这个类有一个方法
public static IEnumerable<T> Sort(IEnumerable<T> list, Func<T, String> field)
基本上它在给定一个返回要排序的值的 Func 的某个列表上执行自然排序。我一直用它来做任何我想做自然排序的事情。
通常我会做类似
sorted = NaturalSort<Thing>.sort(itemList, item => item.StringValueToSortOn)
现在我有这样的情况,我想要排序的值不是项目的字段,而是对某种方法的调用
类似
sorted = NaturalSort<Thing>.sort(itemList, item => getValue(item))
现在如果我 getValue 返回一个对象而不是字符串会怎么样。我需要做一些条件逻辑来获取我的字符串值
sorted = NaturalSort<Thing>.sort(itemList, item => getValue(item).Something == null ? getValue(item).SomethingElse : getValue(item).SomeotherThing)
这会起作用,除了对 getValue 的调用很昂贵而且我不想调用它 3 次。有什么方法可以在表达式内部调用它吗?
First let me say I'm not sure if the title of this question makes any sense, but I'm not sure how to word my problem.
I have a class defined as
public static class NaturalSort<T>
This class has a method
public static IEnumerable<T> Sort(IEnumerable<T> list, Func<T, String> field)
Basically it performs a natural sort on some list given a Func that returns the value to sort on. I've been using this for anything that I want to do a natural sort on.
Normally I would do something like
sorted = NaturalSort<Thing>.sort(itemList, item => item.StringValueToSortOn)
Now I have a case where the value I want to sort on isn't a field of the item, but is a call to some method
Something like
sorted = NaturalSort<Thing>.sort(itemList, item => getValue(item))
Now what if I getValue returns an object instead of a string. and I need to do some conditional logic to get to my string value
sorted = NaturalSort<Thing>.sort(itemList, item => getValue(item).Something == null ? getValue(item).SomethingElse : getValue(item).SomeotherThing)
This would work, except the call to getValue is expensive and I don't want to call it 3 times. Is there some way I can call it once inside the expression?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@Femaref 是 100%,我只是想知道,为什么你不去
@Femaref is 100%, i'm just wondering, why you wouldnt go with
是的,lambda 可以有多行代码。
如果使用
Func
委托,请确保在此语法中返回一个值,虽然这是在短语法中隐式处理的,但您必须在多行语法中自己执行此操作。另外,您应该使您的
Sort
方法成为扩展方法,您也不需要类上的类型参数,只需使用Yes, lambdas can have multiple lines of code.
Make sure you return a value in this syntax if using a
Func<T>
delegate, while this is handled implicitly in the short syntax, you have to do it yourself in the multi-line syntax.Also, you should make your
Sort
method an extension method, you also don't need the type parameter on the class, simply use