2010-06-17 41 views
1

所以,現在我已經有了很多用戶可以排序的列(名稱,縣,活動),這很容易但很混亂。看起來是這樣的......有條件訂單

 Select Case e.SortExpression 
      Case "Name" 
       If (isDescending) Then 
        resultsList.OrderByDescending(Function(a) a.Name).ToList() 
       Else 
        resultsList.OrderBy(Function(a) a.Name).ToList() 
       End If 
      Case "County" ... and so on 

什麼,我想要做的,是更多的東西......優美,像這樣

Private Function SortThatList(ByVal listOfStuff As List(Of Stuff), ByVal isDescending As Boolean, ByVal expression As Func(Of Stuff)) As List(Of Stuff) 
    If (isDescending) Then 
     Return listOfStuff.OrderByDescending(expression) 
    Else : Return listOfStuff.OrderBy(expression) 
    End If 
End Function 

,但它不喜歡的數據類型(中TKEY的) ...我已經厭倦了Func(的東西,布爾)(在C#中有一些很好用的東西),但似乎無法得到這個做我想做的事情。想法?什麼是神奇的語法?

+0

我不知道解決您的問題,但IMO更好的接口將通過添加一個擴展方法來完成,該方法是'OrderBy'的一個重載,但接受一個額外的布爾參數,例如,如果它應該「遞增」地命令,則爲「假」。所以例如'listOfStuff.OrderBy(expression,isDescending)'... – 2010-06-17 17:29:25

+0

你可以發佈C#代碼,以便我們可以看到你要做什麼? – 2010-06-17 17:33:37

+1

有點類似c#的代碼看起來像這樣 public List Get(Expression > expression) – jeriley 2010-06-17 17:38:16

回答

3

在這裏,你需要一個擴展方法,它需要一個額外的參數,在VB中。您可能會丟失的是方法名稱後面的(Of TSource, TKey),相當於C#中的<TSource, TKey>

<Extension()> 
Public Function OrderBy(Of TSource, TKey)(ByVal source As IEnumerable(Of TSource), ByVal isDescending As Boolean, ByVal selector As Func(Of TSource, TKey)) As IOrderedEnumerable(Of TSource) 
    Return If(isDescending, source.OrderByDescending(selector), source.OrderBy(selector)) 
End Function 
0

在C#中接受的答案櫃面有人來尋找

public IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, bool isDescending, Func<TSource, TKey> selector) 
{ 
    return isDescending ? source.OrderByDescending(selector) : source.OrderBy(selector); 
} 

使用

VB

listOfStuff.OrderBy(isDescending, Function(x) x.Name) 

C#

listOfStuff.OrderBy(isDescending, x => x.Name);