重用Func/lambda表达式中的方法调用

Eri*_*rix 2 c# lambda func

首先让我说我不确定这个问题的标题是否有意义,但我不确定如何说出我的问题.

我有一个定义为的类

public static class NaturalSort<T>
Run Code Online (Sandbox Code Playgroud)

这个类有一个方法

public static IEnumerable<T> Sort(IEnumerable<T> list, Func<T, String> field)
Run Code Online (Sandbox Code Playgroud)

基本上,它在某个列表上执行自然排序,给定一个Func,返回要排序的值.我一直在使用它来做任何我想做的事情.

通常我会做类似的事情

sorted = NaturalSort<Thing>.sort(itemList, item => item.StringValueToSortOn)
Run Code Online (Sandbox Code Playgroud)

现在我有一个案例,我想要排序的值不是项目的字段,而是调用某些方法

就像是

sorted = NaturalSort<Thing>.sort(itemList, item => getValue(item))
Run Code Online (Sandbox Code Playgroud)

现在如果我的getValue返回一个对象而不是一个字符串.我需要做一些条件逻辑来获取我的字符串值

sorted = NaturalSort<Thing>.sort(itemList, item => getValue(item).Something == null ? getValue(item).SomethingElse : getValue(item).SomeotherThing)
Run Code Online (Sandbox Code Playgroud)

这可以工作,除了调用getValue是昂贵的,我不想调用它3次.有没有什么方法可以在表达式中调用它一次?

Fem*_*ref 5

是的,lambdas可以有多行代码.

item =>
{
  var it = getvalue(item);
  return it.Something == null ? it.SomethingElse : it.SomeotherThing;
}
Run Code Online (Sandbox Code Playgroud)

如果使用Func<T>委托,请确保在此语法中返回值,而在短语法中隐式处理,您必须在多行语法中自行完成.

此外,您应该使您的Sort方法成为扩展方法,您也不需要类上的类型参数,只需使用

public static IEnumerable<T> Sort<T>(this IEnumerable<T> list, Func<T, String> field)
Run Code Online (Sandbox Code Playgroud)