Sorting Points

  • Thread starter Thread starter shortyes
  • Start date Start date
S

shortyes

Is there any easy way to sort a list of Points by either its X or Y or
both?

Tried
sortedlist (of String, Point) where string is Point.X & "," & Point.Y
as the key
sortedlist (of Point, Point) using the Point as the key

I could always use try and true method of a binary search algorithm
but I rather not.

It seems to be storing it but I can't seem to extract the data
 
Is there any easy way to sort a list of Points by either its X or Y or
both?

Tried
sortedlist (of String, Point) where string is Point.X & "," & Point.Y
as the key
sortedlist (of Point, Point) using the Point as the key

I could always use try and true method of a binary search algorithm
but I rather not.

It seems to be storing it but I can't seem to extract the data

You could write an IComparer that knows how to compare Points by their
coordinates and pass that in to the Sort method of a list.
 
Chris Dunaway said:
You could write an IComparer that knows how to compare Points by their
coordinates and pass that in to the Sort method of a list.

EG


Function CompareX(ByVal a As Point, ByVal b As Point) As Integer
Return a.X.CompareTo(b.X)
End Function

Function CompareY(ByVal a As Point, ByVal b As Point) As Integer
Return a.Y.CompareTo(b.Y)
End Function

Sub Main()

Dim points() As Point = {New Point(3, 4), New Point(1, 5), New Point(7,
2)}
Array.Sort(Of Point)(points, AddressOf CompareX)


Console.WriteLine("Array of points sorted by X")
For Each p As Point In points
Console.WriteLine(String.Format("x={0},y={1}", p.X, p.Y))
Next

Dim pointList As New List(Of Point)(points)
pointList.Sort(AddressOf CompareY)

Console.WriteLine("List of points sorted by Y")
For Each p As Point In pointList
Console.WriteLine(String.Format("x={0},y={1}", p.X, p.Y))
Next

Console.ReadKey()

End Sub



Davud
 
Dim points() As Point = {New Point(3, 4), New Point(1, 5), New Point(7,
2)}
Array.Sort(Of Point)(points, AddressOf CompareX)

How does this work? I cant find a reference in the docs to an
Array.Sort method that takes that kind of delegate? I tested the code
and it works, of course, I am just at a loss to understand how?

Thanks,

Chris
 
Chris Dunaway said:
How does this work? I cant find a reference in the docs to an
Array.Sort method that takes that kind of delegate? I tested the code
and it works, of course, I am just at a loss to understand how?

That's this overload

Public Shared Sub Sort(Of T) ( _
array As T(), _
comparison As Comparison(Of T) _
)
http://msdn2.microsoft.com/en-us/library/cxt053xf.aspx

Which uses the Comparison generic delegate

Public Delegate Function Comparison(Of T) ( _
x As T, _
y As T _
) As Integer
http://msdn2.microsoft.com/en-us/library/tfakywbh.aspx

David
 
Back
Top