对特定对象排序

时间:2017-09-08 13:16:27

标签: vb.net

我有以下树类:

Public Class HtmlSection
        Property Name As String
        Property SubSections As List(Of HtmlSubSection)
End Class

Public Class HtmlSubSection
        Property Name As String
        Property SelectedSentences As List(Of HtmlSentence)
End Class

Public Class HtmlSentence
        Property Sentence As String
        Property Position As Integer   
End Class

在下面的方法中,我正在搜索属于特定部分的每个子部分的所有句子,最后我按位置asc对这些记录进行排序。然而,有时位置必须改变(直接在句子中),因为在我做OrderBy之后可能存在间隙意味着它将被订购,但它可能如下所示。有没有像linq那样简单的方法来改变那些句子的位置以避免间隙让我们在下面显示的方法中说出来。

2
5
77
1001

我想在我们的例子中改变从0开始的位置:

0
1
2
3

方法:

Public Function GetSelectedSentencesOnSectionLevel(section As HtmlSection) As List(Of HtmlSentence)
     Dim sentencesList As New List(Of HtmlSentence)
       For Each exSection As HtmlSection In _htmlFactory.SectionsList
        If exSection.Name = section.Name Then
           Dim sentencesList As New List(Of HtmlSentence)
             If Not IsNothing(exSection.SubSections) Then
                For Each exSubsection As HtmlSubSection In exSection.SubSections
                  If Not IsNothing(exSubsection.SelectedSentences) Then
                    For Each exSentence As HtmlSentence In exSubsection.SelectedSentences
                           sentencesList.Add(exSentence)
                    Next
                  End If
                Next
             End If
        End If       
    Next

'sort sentences by Posiions ascending
sentencesList = sentencesList.OrderBy(Function(x) x.Position).ToList()            
 Return sentencesList
End Function

编辑:更多帮助者代码:

全球课程:

Public Class HtmlFactory
        Property SectionsList As List(Of HtmlSection)

        Sub New()
            SectionsList = New List(Of HtmlSection)
        End Sub

        Sub New(pSectionsList As List(Of HtmlSection))
            _SectionsList = pSectionsList
        End Sub

        Public Sub AddSection(section As HtmlSection)
            SectionsList.Add(section)
        End Sub
....

1 个答案:

答案 0 :(得分:1)

这里是一个纯粹的LINQ解决方案。

Dim index As Integer = -1

Dim sectionName As String

Dim allTheSections As List(Of HtmlSection)

Dim sentenceList = allTheSections _
    .Where(Function(sect) _
               sect.SubSections IsNot Nothing _
               AndAlso sect.Name.Equals(sectionName, StringComparison.OrdinalIgnoreCase)) _
    .SelectMany(Function(sect) sect.SubSections) _
    .Where(Function(subSect) subSect.SelectedSentences IsNot Nothing) _
    .SelectMany(Function(subSect) subSect.SelectedSentences) _
    .OrderBy(Function(ss) ss.Position) _
    .Select(Function(ss)
                index += 1
                Return New HtmlSentence With {.Position = index, .Sentence = ss.Sentence}
            End Function) _
    .ToList()

在此示例中,allTheSectionsexSection来自的地方。