2

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

我有一个类定义为

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 次。有什么方法可以在表达式中调用它一次吗?

4

2 回答 2

5

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

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

如果使用Func<T>委托,请确保在此语法中返回一个值,虽然这在短语法中隐式处理,但您必须在多行语法中自己完成。

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

public static IEnumerable<T> Sort<T>(this IEnumerable<T> list, Func<T, String> field)
于 2011-04-08T14:13:10.757 回答
0

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

sorted = NaturalSort<Thing>.sort(itemList, item => getValue(item))
         .Select(item => item.Something == null ? item.SomethingElse : item.SomeotherThing)
于 2011-04-08T14:19:48.580 回答