ElektroStudios
ElektroStudios

Reputation: 20464

Issue with Lambda to sort a list

I'm using a custom List to store contacts:

    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)

Now what I want to do is to make a generic function to sort or reorder the contacts by a member variable and also specifying ascending or descending mode, I've tried to do this:

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

And I call the function like this:

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

At this point I have two problems:

  1. No idea of how to pass the Ascending/Descending keyword as an argument of the function to use it right.

  2. The function will not sort the list, maybe the problem is in the Lambda expression that I'm using or my checks of Member Expressions because I'm not experienced with these things.

Someone can give me help?

UPDATE:

The Contact class contains those private members:

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

..I think that means I can't pass a lambda like this:

Sort_ContactList(Contacts, Function() Contact.mName)

Upvotes: 1

Views: 117

Answers (1)

sloth
sloth

Reputation: 101072

Why don't you just use OrderBy and OrderByDescending?

OrderBy and OrderByDescending are generic and you can use lambda methods with them.

Instead of:

Sort_ContactList(Contacts, Function() Contact.Name)

simply use:

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

Upvotes: 1

Related Questions