首先让我说我不确定这个问题的标题是否有意义,但我不确定如何表达我的问题。
我有一个类定义为
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 次。有什么方法可以在表达式中调用它一次吗?