簡體   English   中英

重用Func / lambda表達式內的方法調用

[英]reuse a method call inside Func/lambda expression

首先讓我說我不確定這個問題的標題是否有意義,但是我不確定如何措辭我的問題。

我有一個定義為

public static class NaturalSort<T>

這個類有一個方法

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

基本上,在給定Func的情況下,它對某些列表執行自然排序,該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次。 有什么方法可以在表達式內調用一次嗎?

是的,lambda可以包含多行代碼。

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)

@Femaref是100%,我只是想知道,為什么你不願意

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM