【问题标题】:Sort My class by two values按两个值对我的班级进行排序
【发布时间】:2017-01-25 13:49:40
【问题描述】:

我有一个类 MyLines 有 2 个属性,StartPointEndPoint

我还有一个List(Of MyLines)

Dim ListOfLines As New List(Of MyLines)

理论上,所有MyLines 都将在一端匹配为“一系列行”(如果有意义的话) 我想在这个列表上做 3 次操作。

第一次操作: 如果任何MyLines.EndPoint 等于任何其他MyLines.Endpoint,它应该执行SwapEnds 以确保所有数据都是有序的。因为数据应该是SP、EP、SP、EP、SP、EP……

第二次行动: 哪个MyLines.Startpoint 与任何其他MyLines.EndPoint 都不匹配,这个MyLines 应该是新列表的第一个

第三次行动: 然后我想对剩余的MyLines 进行排序,以便每个MyLinesMyLines.EndPoint 与下一个MyLinesMyLines.StartPoint 匹配。

由于数据可能以错误的顺序输入(我创建了一个SwapEnd 方法,但我不知道如何检查)

寻找想法。我会在 VB.net 或 C# 中回答 提前致谢。 :)

Public Class MyLines
Implements IComparable(Of MyLines)

Private m_StartPoint As Point3d
Private m_EndPoint As Point3d

Public Sub New(ByVal StartPoint As Point3d, ByVal EndPoint As Point3d)
    m_StartPoint = StartPoint
    m_EndPoint = EndPoint
End Sub

Public ReadOnly Property StartPoint() As Point3d
    Get
        Return m_StartPoint
    End Get
End Property

Public ReadOnly Property EndPoint() As Point3d
    Get
        Return m_EndPoint
    End Get
End Property

Public Sub SwapEnd()

    Dim OldValue As Point3d = New Point3d(m_StartPoint)
    m_StartPoint = New Point3d(m_EndPoint)
    m_EndPoint = New Point3d(OldValue)
    Debug.Print("Swapped")
End Sub

Public Function CompareTo(other As MyLines) As Integer Implements IComparable(Of MyLines).CompareTo
    Return EndPoint.IsEqualTo(other.StartPoint, New Tol(0.0001, 0.0001))
End Function

【问题讨论】:

  • 三条线在同一点相交会发生什么?通常这是通过将点列表与相邻点列表来完成的,这些点是连接点的线。你交换没有多大意义,因为一条直线是对称的,你会得到与开始时完全相同的结果。
  • 线只会在两端与不同的线相交。可以把它想象成一条带顶点的长线。
  • 路径可以循环返回还是始终向一个方向前进?

标签: c# vb.net linq sorting


【解决方案1】:

保留仍需排序的线段列表open 和已排序线段的列表ordered。前者将是线段的初始列表,后者将开始为空。然后从任何线段开始,尝试在两个方向上找到它的延续:

//Pseudo code
Move first entry from open to ordered
Dim foundNext As Boolean
Do 'Forward direction
    foundNext = False
    For Each segment in open
        If open.Last().EndPoint = segment.StartPoint
            move segment from open to end of ordered
            FoundNext = True
            Continue While
        Else If open.Last().EndPoint = segment.EndPoint
            segment.Swap()
            move segment from open to end of ordered
            FoundNext = True
            Continue While
        End If
     Next
While foundNext
Do 'Backward direction
    foundNext = False
    For Each segment in open
        If open.First().StartPoint = segment.EndPoint
            move segment from open to beginning of ordered
            FoundNext = True
            Continue While
        Else If open.Last().StartPoint = segment.StartPoint
            segment.Swap()
            move segment from open to beginning of ordered
            FoundNext = True
            Continue While
        End If
     Next
While foundNext

【讨论】:

    猜你喜欢
    • 2014-10-20
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2015-04-14
    • 2016-07-13
    • 2023-01-26
    相关资源
    最近更新 更多