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

时间:2011-04-08 14:10:42

标签: c# lambda func

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

我有一个定义为

的类
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次,否则这会有效。有没有什么方法可以在表达式中调用它一次?

2 个答案:

答案 0 :(得分:5)

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

item =>
{
  var it = getvalue(item);
  return it.Something == null ? it.SomethingElse : it.SomeotherThing;
}

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

另外,你应该使你的Sort方法成为扩展方法,你也不需要类上的type参数,只需使用

public static IEnumerable<T> Sort<T>(this IEnumerable<T> list, Func<T, String> field)

答案 1 :(得分:0)

@Femaref是100%,我只是想知道,为什么你不跟

一起去
sorted = NaturalSort<Thing>.sort(itemList, item => getValue(item))
         .Select(item => item.Something == null ? item.SomethingElse : item.SomeotherThing)