所以,现在我有一些用户可以排序的列(名称,县,活动),这很简单但很麻烦。看起来像这样...
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
但是它不喜欢数据类型(Of TKey)...我已经厌倦了Func(Of stuff,boolean)(在c#中得到了一些很好用的东西)但似乎无法得到这个做我想做的。想法?什么是神奇的语法?
答案 0 :(得分: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
答案 1 :(得分: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);