2013-10-14 77 views
1

我使用自定義列表存儲聯繫人的列表:問題和λ排序

Dim Contacts As List(Of Contact) = New List(Of Contact) 

    ' Create a new contact 
    Dim CurrentContact As Contact = New Contact With { _ 
     .Name = "Manolo el del Bombo", _ 
     .Country = "Spain", _ 
     .City = "Valencia", _ 
     .Street = "Av. Mestalla", _ 
     .ZipCode = "42731", _ 
     .Phone = "96.XXX.XX.XX", _ 
     .CellPhone = "651.XXX.XXX", _ 
     .Email = "[email protected]"} 

    ' Add a contact to contacts list 
    Contacts.Add(CurrentContact) 

現在我想要做的就是讓一個泛型函數進行排序或重新排序由成員變量的接觸並指定升序或降序方式,我試着這樣做:

Private Function Sort_ContactList(ByVal ContactList As List(Of Contact), _ 
            ByVal Field As Expressions.Expression(Of Func(Of Object))) As List(Of Contact) 

    Dim member As Linq.Expressions.MemberInitExpression = _ 
     If(TypeOf Field.Body Is Linq.Expressions.UnaryExpression, _ 
     DirectCast(DirectCast(Field.Body, Linq.Expressions.UnaryExpression).Operand, Linq.Expressions.MemberInitExpression), _ 
     DirectCast(Field.Body, Linq.Expressions.MemberInitExpression)) 

    ' MsgBox(OrderedContacts.First.Name & " " & OrderedContacts.First.Country) 
    Return (From contact In ContactList Order By member Ascending Select contact).ToList() 

End Function 

我這樣調用該函數:

Contacts = Sort_ContactList(Contacts, Function() New Contact With {.Name = Nothing}) 

在這一點上我有兩個問題:

  1. 如何上升/下降關鍵字傳遞作爲函數的參數使用它的權利不知道。

  2. 該函數不會對列表進行排序,可能問題出在我正在使用的Lambda表達式或我對會員表達式的檢查中,因爲我沒有經歷過這些事情。

有人能幫我嗎?

UPDATE:

Contact類包括那些私有成員:

Private mId As System.Guid 
Private mName As String 
Private mCountry As String 
Private mCity As String 
Private mStreet As String 
Private mZip As String 
Private mPhone As String 
Private mCellPhone As String 
Private mEmail As String 

..我想這意味着我無法通過這樣的拉姆達:

Sort_ContactList(Contacts, Function() Contact.mName) 
+0

你爲什麼不只是使用'OrderBy'和'OrderByDescending'? – sloth

+0

@Dominic Kexel感謝評論,但使用其他任何(的.sort + Comparers,.Orderby + Thenby)我會得到同樣的問題,因爲通常的排序是容易的,但就像我說的,我需要使它通用的分揀一個使用lambda的函數,而且對我來說不是一件容易的事情。 – ElektroStudios

+1

'OrderBy'和'OrderByDescending'是通用的,你可以用與他們拉姆達方法,所以我還沒有看到這個問題。取而代之的'Sort_ContactList(觸點,功能()Contact.Name)'爲什麼不'Contacs.OrderBy(功能(C)c.Name)'? – sloth

回答

1

何不「T你只需要使用OrderByOrderByDescending

OrderByOrderByDescending是通用的,你可以使用拉姆達方法與他們。

相反的:

Sort_ContactList(Contacts, Function() Contact.Name) 

簡單地使用:

Contacs.OrderBy(Function(c) c.Name)