Finding the highest integer in a set of numbers or string of numbers

Hello, I have an xml file containing a number of news items each with a unique id field. What i'm trying to do is finish off my add news procedure.
So far it creates the new item fine, all that remains is to get the program to make the variable, for the id) one higher than the biggest id already in the xml file.
I'll try to explain:

xml file has many items e.g.:
<item id="4">
<item id="8">
<item id="9"> etc.

and i can get those id's and put them in a long string like this:
|4||8||9| (The |'s are to separate the numbers up so you don't get 148921, because from this my program wouldn't be able to tell the difference between 1 and 21, but can with |1||21|)

What i'd like to do is to get the highest number, in this case 9, and increase it by one for the new news item. I had a look at the math.max, but it finds the larger of two numbers : - /.

Could anyone offer any suggestions
Cheers
-- Ash Clarke



Answer this question

Finding the highest integer in a set of numbers or string of numbers

  • remisp

    Thank you so much. It worked with a slight modification to prevent an exception. The s.split("|") created an array (sa() ) with entries of "" and "4", "", "5", "", etc so I modified:

    If Convert.ToInt32(sa(x)) > LargestNumber Then

    LargestNumber = sa(x)

    End If

    To:

    If Not sa(x) = nothing then

    If Convert.ToInt32(sa(x)) > LargestNumber Then

    LargestNumber = sa(x)

    End If

    End If

    So Thank you again.
    Cheers
    -- Ash Clarke


  • Stephen Toub - MSFT

    Private Function GetLargestNumberFromString(ByVal s As String) As Integer

    Dim sa() As String = s.Split("|")

    Dim LargestNumber As Integer = 0

    For x As Integer = 0 To UBound(sa)

    Try

    If Convert.ToInt32(sa(x)) > LargestNumber Then

    LargestNumber = sa(x)

    End If

    Catch ex As Exception

    End Try

    Next

    Return LargestNumber

    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim S As String = "|4||5||6||9||1||2|"

    MessageBox.Show(GetLargestNumberFromString(S))

    End Sub



  • Finding the highest integer in a set of numbers or string of numbers