Convert a string like "1,2,3,4,5,6,7,8,9,11,12,13,15" to "1 to 9, 11 to 13, 15"

I have a database field which holds serial numbers as a comma separated string which has already been checked for duplicates and sorted.

This field can be very large when there are many serial numbers. In order to save screen space I would like to display ranges of sequential numbers by showing the first and last number with "to" between them. This may happen a few times in one string. I've tried fiddling around putting the string into an arraylist but my mind goes blank when trying to work out how to know if a number is the next in sequence when moving through the arraylist. I have googled the problem but I guess I'm looking in the wrong direction as none of my searches turned up the goods.

 Any help would be greatly appreciated

Paul


To understand the heart and mind of a person , look not at what he has already achieved, but what he aspires to.
0
SlugZen
1/27/2009 5:55:07 PM
asp.net.visual-basic.net 3721 articles. 0 followers. Follow

5 Replies
975 Views

Similar Articles

[PageSpeed] 20

Hi Paul:

Do you prefer C# or VB?

I see a variable called lowinteger initially storing the first number. (some trickery involving boolean trip triggers may be needed to get things going)

a foreach loop cycles through all the numbers (which we've moved to an integer array using .Split).

At each new number it sees the current number as current number and it remembers the previous numer as previous number

if the next number is one higher, nothing happens other than previous number takes the value of current number

if the next number is more than one higher then it takes low integer and previous number and writes

lowestnumber + " to " + previousnumber

and now previous number becomes the lowest number

and the cycle repeats.

I'm going to assume you like C# and start working on it (it was the most interesting question I've seen yet today) but if you prefer VB I'll switch over to that.

 

 


Larry Dechent - Sampson Coatings

www.wemakebetterpaint.com has 29 examples (C# & VB) to help beginners with ASP.NET.
0
ldechent
1/27/2009 6:24:41 PM

Hi Idechent

Thanks for the quick reply. I'm in the UK and finishing work for the day but before I go I thought I'd better say that I'd prefer an answer in VB. Glad I managed an interesting question and I look forward to your suggestion when I get back in the morning.

 

Many Thanks

 

Paul


To understand the heart and mind of a person , look not at what he has already achieved, but what he aspires to.
0
SlugZen
1/27/2009 6:48:18 PM

 

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Paul_VB.aspx.vb" Inherits="Paul_VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Button ID="ActionButton" runat="server" Text="Do It" 
            onclick="ActionButton_Click" /><br /><br />
            
        <asp:Label ID="ShowMeLabel" runat="server" Text="Label"></asp:Label>
        
    </div>
    </form>
</body>
</html>

 

  

 
Partial Class Paul_VB
    Inherits System.Web.UI.Page

    Protected Sub ActionButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ActionButton.Click

        'Chose one and comment out the other -- both need to be tested
        'Dim commanumbers As String = "1,2,3,4,5,6,7,8,9,11,12,13,15"  'last number is single
        Dim commanumbers As String = "1,2,3,4,5,6,7,8,9,11,12,14,16,17,20,21"  'last number is in a range

        Dim individuals As String() = commanumbers.Split(",")

        ShowMeLabel.Text = "the numbers...<br /><br />"

        For Each individual As String In individuals

            ShowMeLabel.Text += individual & " "

        Next

        ShowMeLabel.Text += "<br /><br />"

        ShowMeLabel.Text += "where the breaks occur...<br /><br />"


        Dim toggle As Integer = 1
        Dim currentnumber As Integer = 0
        Dim previousnumber = 0
        Dim difference As Integer

        For Each individual As String In individuals

            currentnumber = Convert.ToInt32(individual)
            If (toggle = 1) Then
                previousnumber = currentnumber
                toggle = 0
            End If
            difference = currentnumber - previousnumber
            If (difference > 1) Then
                ShowMeLabel.Text += " * " 'seeing this proves the program went into the loop
            End If
            ShowMeLabel.Text += individual & " "
            previousnumber = currentnumber

        Next

        Dim lowestnumber As Integer = 0
        ShowMeLabel.Text += "<br /><br />"
        ShowMeLabel.Text += "the ranges...<br /><br />"
        toggle = 1

        For Each individual As String In individuals
            currentnumber = Convert.ToInt32(individual)
            If (toggle = 1) Then
                lowestnumber = currentnumber
                previousnumber = currentnumber
                toggle = 0
            End If
            difference = currentnumber - previousnumber
            If (difference > 1) Then
                If (previousnumber = lowestnumber) Then 'we have a single value
                    ShowMeLabel.Text += previousnumber.ToString() & ", "
                Else
                    ShowMeLabel.Text += lowestnumber.ToString() & " - " & previousnumber.ToString() & ", "
                End If
                lowestnumber = currentnumber
            End If
            previousnumber = currentnumber
        Next

        'we're not done quite yet and we could have a single value or a range for the last segment

        If (currentnumber = lowestnumber) Then  'we have a single value
            ShowMeLabel.Text += currentnumber.ToString()
        Else
            ShowMeLabel.Text += lowestnumber.ToString() & " - " & currentnumber.ToString()
        End If

    End Sub
End Class
  
Larry Dechent - Sampson Coatings

www.wemakebetterpaint.com has 29 examples (C# & VB) to help beginners with ASP.NET.
0
ldechent
1/27/2009 7:54:41 PM

 Hi Paul:

The code behind has two possible strings to test, one that ends with the last "thing" being a single value and the other with the last "thing" being a series.

I also tested it with

"1,2,3,4,5,6,7,8,9,11,12,14,16,17,20,21"

to have an 'interior" single value (and promptly found I forgot to code for this condition).

I'll put some more test results here. 

A "thing" can be a single number, a range (and a range can be adjacents, x and x+1 or more than just adjacents).

A thing could be located at the beginning, in the middle or at the end.  I think this 3 x 3 covers all possibilities

  • "1,3,4,5,6,7,8,9,11,12,14,16,17,20,21" / 1, 3 - 9, 11 - 12, 14, 16 - 17, 20 - 21

  • "1,2,4,5,6,7,8,9,11,12,14,16,17,20,21" / 1 - 2, 4 - 9, 11 - 12, 14, 16 - 17, 20 - 21

  • "1,2,4,5,6,7,8,9,11,12,14,16,17,20,21,22,23,24,25" / 1 - 2, 4 - 9, 11 - 12, 14, 16 - 17, 20 - 25

  • "1,2,4,5,6,7,8,9,11,12,14,16,17,20,21,22,25" / 1 - 2, 4 - 9, 11 - 12, 14, 16 - 17, 20 - 22, 25


Larry Dechent - Sampson Coatings

www.wemakebetterpaint.com has 29 examples (C# & VB) to help beginners with ASP.NET.
0
ldechent
1/27/2009 8:00:39 PM

Hi Idechent.

Thanks loads for your help. It was the kick in the brain I need to get things going. I took your code and put it in a function so I could use it anywhere in my site.

I realised that because the Serial No's are converted to integers for sorting and removal of duplicates that I needed to add a bit extra to store the length of the Serial No and any alphabetical prefix so that I could put them back before sending the text to screen. My code probable doesn't cover every eventuality but it's working so far with the Serial No's I have to deal with. Lastly if there were only 2 numbers in a sequence I felt it was better to have a comma between them rather than "to" so I added an extra bit where the output string is created.

 

 

    Shared Function SerialNumbersSimplify(ByVal SerialNumberString As String) As String
        SerialNumberString = Regex.Replace(SerialNumberString, "-|^[ \t]+|[ \t]+$", ",")

        Dim outputString As String = ""
        If Not SerialNumberString.Length() = 0 Then
            Dim individuals As String() = SerialNumberString.Split(",")
            Dim toggle As Integer = 1
            Dim currentnumber As Integer = 0
            Dim previousnumber = 0
            Dim difference As Integer
            Dim lowestnumber As Integer = 0
            Dim prefix As String = Regex.Replace(individuals(0), "\d", "")
            Dim snLength As Integer = Regex.Replace(individuals(0), "\D", "").Length()


            For Each individual As String In individuals
                currentnumber = Convert.ToInt32(Val(Regex.Replace(individual, "\D", "")))
                If (toggle = 1) Then
                    lowestnumber = currentnumber
                    previousnumber = currentnumber
                    toggle = 0
                End If
                difference = currentnumber - previousnumber
                If (difference &gt; 1) Then
                    If (previousnumber = lowestnumber) Then 'we have a single value
                        outputString += prefix & previousnumber.ToString().PadLeft(snLength, "0") & ", "
                    ElseIf (previousnumber - 1 = lowestnumber) Then
                        outputString += prefix & lowestnumber.ToString().PadLeft(snLength, "0") & ", " & prefix & previousnumber.ToString().PadLeft(snLength, "0") & ", "
                    Else
                        outputString += prefix & lowestnumber.ToString().PadLeft(snLength, "0") & " to " & prefix & previousnumber.ToString().PadLeft(snLength, "0") & ", "
                    End If
                    lowestnumber = currentnumber
                End If
                previousnumber = currentnumber
            Next

            'we're not done quite yet and we could have a single value or a range for the last segment

            If (currentnumber = lowestnumber) Then  'we have a single value
                outputString += prefix & currentnumber.ToString().PadLeft(snLength, "0")
            ElseIf (currentnumber - 1 = lowestnumber) Then
                outputString += prefix & lowestnumber.ToString().PadLeft(snLength, "0") & ", " & prefix & currentnumber.ToString().PadLeft(snLength, "0")
            Else
                outputString += prefix & lowestnumber.ToString().PadLeft(snLength, "0") & " to " & prefix & currentnumber.ToString().PadLeft(snLength, "0")
            End If
        End If

        Return outputString

    End Function
 
To understand the heart and mind of a person , look not at what he has already achieved, but what he aspires to.
0
SlugZen
2/3/2009 1:43:07 PM
Reply:

Similar Artilces:

Paging Repeater treating page 11 as "1" and "1" not "11"
Dear AllI have a paging repeater, and I am displaying pages according to the amount of records I am retreiving from the database.  My code is as follows:-ASPX           <asp:Repeater runat="server" ID="rptPageNumbers" OnItemCommand="rptPageNumbers_ItemCommand">              <ItemTemplate>                <asp:LinkButton ID="LinkButton1" runat=&quo...

Problem with upgrade from 11.5.1 to 12.5.2
I am upgrading an 11.5.1 server to 12.5.2. I ran the sqlupgrade utility in non-upgrade mode and fixed up the issues it threw up. There is one remaining issue which I cannot fix. The sqlupgrade utility say that I must set the "esp execution stacksize" server parameter value to a min of 50000. However when I attempt to change this on my 11.5.1 server I get the following error message. ------------------------------------------------------------------------------- 1> sp_configure "esp execution stacksize", 50000 2> go Msg 5846, Level 16, State 1: S...

Bcp utility "-n" parameter failed between 11.9.2 and 11.5.1
Hello, Recently I received a bcp export from a client who uses Sybase 11.9.2 . The client used "native format" as indicated by the "-n" parameter. When I tried to import the file in my server (11.5.1) it failed. It did not give any error messages and the log file simply stated that 0 rows were copied, but there are two rows in the export file. Is there any diference in the native format of versions 11.9.2 and 11.5.1? Can someone explain why this is happening? Thanks in advance. Jorge Vergara. "Jorge Lu�s Vergara" wro...

selecting ? selecting of 1., 2. , 3., 4., 5., 6. is slow (1-3 second) then selecting of 7.,8.,9. go on is so fast (0.1 second or more fast).. how can i get fast for selecting of 1., 2. , 3., 4., 5., 6
hello friends selecting of 1., 2. , 3., 4.(sometime even 5., 6.) is slow (1-3 second) then selecting of 7.,8.,9.(sometimes 5., 6.,) go on is so fast (0.1 second or more fast).. how can i get fast for selecting of 1., 2. , 3., 4., 5., 6. is slow ?? recordcount is almost 1.050.000.. i do selecting 1.2.3. go on same page with treeview1.. treeview1 in masterpage.master.. gridview1 and datasource1 are in pagelist.aspx (it connets datasource1)..productnumber is primarykey for index.. kategori, kategori1 and kategori2, price, datemin are index from keys/index in table1 (right clicking menu)....

Firefox "Lorentz" and 1.9.2/1.9.3
Because information and proposals have been trickling out through the wiki pages and the weekly meeting notes, I'd like to follow up with a longer-form version of why I think we should do Firefox "Lorentz" in March 2010 based off of the 1.9.2 branch. At the Firefox work week I sat at a whiteboard with Beltzner and some others thinking about the features that the Firefox team wants to ship in 2010: * Crash-safe plugins (OOPP) * Transition to jetpack extensions * New UI "stuff": the new menu/toolbar structure and platform integration * Weave * Updater wh...

Error "Make sure that CD number 1 is in your drive." when installing Open SUSE 11.2, 11.3 and 11.4.
Hi sir, I had download the iso of Open SUSE 11.2, 11.3 and 11.4 and confirmed with the MD5 code. Then, I burned them using the lowest speed which the system supported. But the error message "Make sure that CD number 1 is in your drive." is always displayed while installing OS. How can I do? Environment: CPU i7-2710QE. PCH: B1 stepping. Platform: Huron River based. RAM: 2Gx1 unbuffered none ECC RAM. Target OS: Open SUSE 11.2, 11.3 and 11.4 for 32bit. Hdd: WD 160G SATA HDD using IDE mode by setting setup. DVD: Pioneer DVR-217BK. USB keyboard/mouse. Onboard VGA por...

[11.2] kwrite from kde 4.3.1 "release 6"
Quick questions: Have anybody problem with tab key? I made no changes and when I press tab key, I've got only 2 chars tab width. -- Coolmax89 ------------------------------------------------------------------------ Settings>Configure Editor>Editing -- john_hudson ------------------------------------------------------------------------ john_hudson's Profile: http://forums.opensuse.org/member.php?userid=1134 View this thread: http://forums.opensuse.org/showthread.php?t=426590 ...

Opensuse 11.4 with KDE 4.7.2: error when launching "solar system plasmoid" (not a 12.1 thread)
Hello everybody. I am updating a machine with 11.4. As of versions and kernel (and repos) we have: Code: -------------------- uname -a Linux linux-fces 2.6.37.6-0.9-desktop #1 SMP PREEMPT 2011-10-19 22:33:27 +0200 x86_64 x86_64 x86_64 GNU/Linux -------------------- Repos are: Code: -------------------- # zypper repos # | Alias | Name | Enabled | Refresh ---+-----------------------------------------------------+-------------------------------------------------...

Difference between passing "?" versus ":1", ":2", ":3" etc in prepare in Perl DBI !
------=_Part_26521_25854351.1225691891708 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi What's the difference between passing "?" versus ":1", ":2", ":3" etc in prepare in Perl DBI ? For example, what's the difference between following two scenarios :- *Scenario 1* $sth = $dbh->prepare("insert into tablename values (:1, :2, :3)"); $sth->execute($var1,$var2,$var3); *Scenario 2* $sth = $dbh->prepare("insert into tablename values (?, ?, ...

Can anyone tell me the diff between .net framework versions "1.1.4322.573" and "1.1.4322.903"
Production environment is running 1.1.4322.573 Pre Production environments are running 1.1.4322.903 We are seeing some javascript errors that are only happening in our production environment. All of our pre production environments for testing, development and what not seem to be running fine. We get the generic client side error that says which line, which char number and the brief description. The actuall error states "Expected ';' " . Here is the line of code that it's complaining about. "theform = document._ctl6:Form1;" This is microsoft ge...

"create index" much slower with 15.0.3 ESD#1 vs. 15.0.2 ESD#1
I recently upgraded our development server from ASE 15.0.2 ESD#1 to 15.0.3 ESD #1 (EBF 16555). Soon afterward, I noticed that ingests were taking *much* longer than they were previously. A "bcp in" and a dozen "create index" statements on a ~1000-row, ~20-column table is taking ~9 minutes with ASE 15.0.3 ESD#1. With 15.0.2 ESD#1, the same ingest on identical hardware takes ~8 seconds. Both the "create index" statements and the "bcp in" are taking longer. This is on 32-bit Linux with raw partitions, by the way. I thought it might have something ...

Gecko 1.9/Firefox 3 ("Gran Paradiso") Planning Meeting, Wednesday Jun 7, 11:00 am
We'll be holding the first (in recent history, at least) Gecko 1.9/Firefox 3 ("Gran Paradiso" [1]) planning meeting next Wednesday at 11am. This meeting will be held every other week, and will transition into a weekly meeting when necessary. The goal of these meetings is to plan what will become part of the Gecko 1.9 platform and the Firefox 3 product. We'll be starting this process by focusing on the platform (Gecko 1.9) work, but will also soon be asking for input on what we think the goals for the Firefox 3 release should be. There are a lot of idea...

Upgrading from 1.1.11 to 1.1.12 Spell "language extension"
A long time ago, i find how to add "French" into the "Spell" options. The question is: I will simply upgrade from 1.1.11 to 1.1.12 by de-installing 1.1.11 then installing 1.1.12 when SM is not running. So far, so good ... but what will happen with my added option ? Must i remove it before the upgrade ? If yes ... how ? Will "French" dissappear if i had not removed it before the upgrade ? If removed, or dissappeared then i just need to reinstall the French: installable language pack from http://www.seamonkey-project.org/releases/ If not removed...

Swap a "1" or "0" for a "Y" or "N"
I have a sql query that returns rows of data and one field returns a 1 (which means yes) or a 0 (which means no).  On my vb.net page, how do I replace the 1 with a Yes and the 0 with a No?  Or do I do this in the sql?  How do I do this in sql?Never make important decisions on a Monday! By default, VB.Net can understand 1 as Yes and 0 as No.I believe you are using those DB values for your Boolean Operations.Try to use If <DBValue> then <Operation>. If you are really need Yes/No .... Declare boolean variable in VB.net and set those variables. Thanks and R...

Web resources about - Convert a string like "1,2,3,4,5,6,7,8,9,11,12,13,15" to "1 to 9, 11 to 13, 15" - asp.net.visual-basic.net

Resources last updated: 1/15/2016 3:58:00 AM