Tao Gómez Gil
Tao Gómez Gil

Reputation: 2695

Pass constraint as argument

I have a list of lines, each of them with a list of points (x, y). I want to find the biggest "x" in all the lines, so I have written the following function:

Private Function ObtainMaxX() As Double
    Dim maxX As Double = Double.MinValue

    For Each l As Line In _lines
        Dim points As List(Of Point) = l.ObtainPoints
        For Each p As Point In points 
            If p.X > maxX Then
                maxX = p.X
            End If
        Next
    Next

    Return maxX

End Function

Everything works fine. But now I want to obtain the smaller "x" in all the lines. So the function needed to do so would be almost the same to the previous one, except than we would change "Double.MinValue" for "Double.MaxValue" and ">" for "<".

Do you know any way of doing all this stuff in a simpler way, without code duplication?

Thanks!

Upvotes: 1

Views: 51

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460068

You can use Enumerable.Min/Max which are part of the System.Linq namespace:

Dim maxX As Double = c.ObtainLines.Select(Function(p) p.X).Max()
Dim minX As Double = c.ObtainLines.Select(Function(p) p.X).Min()

So you just have to Select the X property first.

Edit: if you want to find the biggest/smallest X overall you can use SelectMany:

Dim allPoints = _lines.SelectMany(Function(l) l.ObtainLines)
Dim maxX = allPoints.Select(Function(p) p.X).Max()
Dim minX = allPoints.Select(Function(p) p.X).Min()

The same in query syntax:

Dim allPointX = From line in _lines
                From point in l.ObtainLines
                Select point.X
Dim maxX = allPointX.Max()
Dim minX = allPointX.Min()

Upvotes: 4

Related Questions