我正在使用自定义列表来存储联系人:
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 = "ManoloToLoko@Gmail.es"}
' 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})
此时我有两个问题:
不知道如何将Ascending / Descending关键字作为函数的参数传递给它使用它。
该函数不会对列表进行排序,可能问题在于我正在使用的Lambda表达式或我对成员表达式的检查,因为我对这些事情没有经验。
有人可以帮我吗?
更新:
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
..我认为这意味着我无法通过这样的lambda:
Sort_ContactList(Contacts, Function() Contact.mName)
答案 0 :(得分:1)
为什么不使用OrderBy
和OrderByDescending
?
OrderBy
和OrderByDescending
是通用的,您可以使用lambda方法。
而不是:
Sort_ContactList(Contacts, Function() Contact.Name)
只需使用:
Contacs.OrderBy(Function(c) c.Name)