我觉得这个功能太长了。我可以将它分成两个函数,但我更愿意将它们保存在一个函数中。
Public Function getTempList(ByVal applicationType As String) As List(Of String)
Dim doc As XDocument = New XDocument
If My.Settings.sortKey = "alpha" Then
Dim XMLquery = From c In doc.<applications>.<app> _
Where c.<appFav>.Value = "true" And c.<appType>.Value = applicationType
Order By CStr(c.<appName>.Value)
Select c.<appName>
Dim tempList As New List(Of String)
For Each result In XMLquery
tempList.Add(result.Value)
Next
Return tempList
ElseIf My.Settings.sortKey = "fav" Then ' ------------------------------------------------------------------------------------
Dim XMLquery = From c In doc.<applications>.<app> _
Where c.<appFav>.Value = "true" And c.<appType>.Value = applicationType
Order By CInt(c.<appClick>.Value) Descending
Select c.<appName>
Dim tempList As New List(Of String)
For Each result In XMLquery
tempList.Add(result.Value)
Next
Return tempList
End If
End Function
我可以以某种方式将if语句放在LINQ查询本身中。这里唯一需要改变的是列表所在的顺序。或者,是否有其他方式来订购我要返回的结果?
答案 0 :(得分:1)
试试这个,
Public Function getTempList(ByVal applicationType As String) As List(Of String)
Dim doc As XDocument = New XDocument
Dim XMLquery = From c In doc.<applications>.<app> _
Where c.<appFav>.Value = "true" And c.<appType>.Value = applicationType
Select c
Dim tempList As New List(Of String)
If My.Settings.sortKey = "alpha" Then
XMLquery = XMLquery.OrderBy(Function(c) CStr(c.<appName>.Value))
ElseIf My.Settings.sortKey = "fav" Then
XMLquery = XMLquery.OrderByDescending(Function(c) CInt(c.<appClick>.Value))
End If
For Each result In XMLquery
tempList.Add(result.<appName>.Value)
Next
Return tempList
End Function
答案 1 :(得分:1)
我认为这是最简单的:
Public Function getTempList(ByVal applicationType As String) As List(Of String)
Dim doc As XDocument = New XDocument
Dim XMLquery = _
From c In doc.<applications>.<app> _
Where c.<appFav>.Value = "true" And c.<appType>.Value = applicationType _
Select c
If My.Settings.sortKey = "alpha" Then
XMLquery = XMLquery.OrderBy(Function(c) CStr(c.<appName>.Value))
ElseIf My.Settings.sortKey = "fav" Then
XMLquery = XMLquery.OrderByDescending(Function(c) CInt(c.<appClick>.Value))
End If
Return XMLquery.Select(Function(x) x.<appName>.Value).ToList()
End Function
答案 2 :(得分:0)
您无需重复整个查询。
您可以执行以下操作:
请原谅我的VB语法,我通常用C#编写代码。
Public Function getTempList(ByVal applicationType As String) As List(Of String)
Dim doc As XDocument = New XDocument
Dim tempList As New List(Of String)
Dim XMLquery = From c In doc.<applications>.<app> _
Where c.<appFav>.Value = "true" And c.<appType>.Value = applicationType
Select c.<appName>
If My.Settings.sortKey = "aplha" Then
Order XMLQuery By CStr(c.<appName>.Value) // convert to VB code
If My.Settings.sortKey = "fav" Then
Order XMLQuery By CInt(c.<appClick>.Value) Descending //convert to VB code
For Each result In XMLquery
tempList.Add(result.Value)
Next
Return tempList
End Function