Convert Structure to String in VB.Net

Posted on 2004-10-19
Last Modified: 2008-01-09
Hello Experts,

I am in the process of converting a VB6 program to  This program build data in a structure; converts the structure to a string; tables the restulting strings in a string array; sorts the array; and then converts the strings back to a structure for additional processing.  I guess the goal here is to build an array of sorted structures.  The conversion to a string is just for sorting.  The strings are also logged in a file.

If I went with an array of structures, the sort routine would have to be reprogrammed to handle sorting structures (and would probably be very slow).  Thus, if I could continue with the VB6 theory of converting the structures to strings, the sort could remain as is.  In VB6, the conversion from structure to string is using the CopyMemory API.  This API did not convert properly and I am having trouble figuring out how to convert the API to .net.  In addition, if I could get rid of that API, I would like to do that.

Does anyone have any advice on what I should do here?  Any help will be appreciated.

Question by:GeneM
  • 3
  • 3
  • 2
LVL 27

Expert Comment

ID: 12347359
Some code would be nice...

There is ways to use structures as string arrays, but need more info from you.

Accepted Solution

GohdanTheMoblin earned 250 total points
ID: 12347548
I'm fairly certain you are making life a little tougher than it is.  How are you sorting the structures?  My guess is there are one or more member variables that are used to perform the sorting.  I think you can make VB do most of the work for you.

IComparable interface:

CompareTo method:

When your structure implements IComparable, it can be automatically sorted by using the Sort method of the Array class.

Here's an example:

First, define a structure that needs to be sorted and implements IComparable.  In this case, a structure is considered greater than another based on the ID member:

==========Begin Code==========
Public Structure TestStructure
    Implements IComparable

    Public ID As Integer
    Public name As String

    Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
        Dim rhs As TestStructure = CType(obj, TestStructure)

        If Me.ID > rhs.ID Then
            'This object's ID is greater than the compared object's ID, so return 1
            Return 1
        ElseIf Me.ID = rhs.ID Then
            'This object's ID is equal to the compared object's ID, so return 0
            Return 0
            'This object's ID must be less than the compared object's ID, so return -1
            Return -1
        End If
    End Function
End Structure
==========End Code==========

Now, here's a console program that creates an array of these structures and sorts the array:

==========Begin Code==========
Module Module1

    Sub Main()
        Dim RNG As New Random

        Dim test(10) As TestStructure

        'initialize the structures in the array
        For i As Integer = 0 To test.Length - 1
            test(i).ID = RNG.Next(0, 10000)
            test(i).name = "Structure" & i.ToString

        'Print initial values

        'sort the array

        'Print the sorted array

    End Sub

    Private Sub PrintArray(ByVal theArray() As TestStructure)
        Console.WriteLine("Printing Array:")
        For Each item As TestStructure In theArray
            Console.WriteLine(item.ID.ToString & vbTab &
    End Sub

End Module
=========End Code=========

The criteria for sorting may be more advanced, but you can work whatever logic you want into CompareTo().  If you still want to copy the objects to strings and back, there are several approaches, but all of them involve significantly more work than this.

Author Comment

ID: 12347854
OK.  Here is some code.  I am giving you the VB6 code:

In a module I have the structure:
Public Type DetailRec
    Name        As String * 26
    RecType     As String * 2
    Space1      As String * 1
    DID         As String * 4
'   Many other variables in here removed, but all
'   are strings and have a fixed length.
End Type

Now in my form, I build the structure detdata of type DetailRec.  This is done in a loop, as I build many data records:

Private Sub btnProcess_Click()
    Dim detdata As DetailRec
    Dim DetDataArray() As String
    n = 1
    Do Until EOF(1)
        detdata.Name = ...some string
        detdata.RecType = ...some string
        detdata.Space1 = " "
        detdata.DID = ...some string

        ReDim Preserve DetDataArray(n) As String
        DetDataArray(n) = Space$(Len(detdata))
        CopyMemory ByVal DetDataArray(n), detdata, Len(detdata)
        n = n + 1
This shows building the string array from the UDT.
The string array is now sorted.  The strings are then extracted from the array and convered back to UDTs by reversing the CopyMemory above.

I hope this helps.
VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

LVL 27

Expert Comment

ID: 12348241
How is your data coming into you? A text file, a database?

Author Comment

ID: 12351594
Hi Planocz,

The data is coming in from a couple of different text files.  There is quite a bit of data manipulation and extraction prior to the building of the UDT as I show in my example.  

If you are thinking I could sort the data prior to building the UDT, that is possible, but I use the UDT to make it easier to keep track of all the data elements.


Expert Comment

ID: 12352396
I'm having trouble understanding exactly why it has to be done with strings, it seems to me that using IComparable wouldn't be a significant performance drain compared to creating a new variable, converting everything to a string, doing the same thing IComparable does with the string, then creating brand new objects from the sorted strings. The ReDim Preserve alone is a massive performance drain.  

 I'm also unclear on just what "sorted" means.  From the code you have posted, I would assume you are parsing the string to get a certain variable and sorting based off of that.  Why take 4 steps to do a 1-step job?

Author Comment

ID: 12352822
Hi GohdanTheMoblin
A couple of things:

This is a running VB6 program.  I am trying to minimize the changes in going to .net.  There are some other functions that are dependent on the strings.  For example, the strings are written out to a file for audit purposes.  The auditor uses Excel to look at the strings.  

IComparable is totally new to me.  Your example is very good, so it looks like I should be able to implement it.  I have not ruled out using Icomparable.  I just thought I would wait and see what Planocz (or someone else) suggests.

Regarding how the strings are sorted, the UDT is constructed so the sort key is at the beginning of the string.  It actually covers several data elements, but they are adjacent on the left part of the string.

Thanks for your comments thus far.


LVL 27

Expert Comment

ID: 12404156
"I am trying to minimize the changes in going to .net." do the kind of data reading and transfering that you are talking about will take a complete convertion to .NET to really see the power and speed that I think you are looking for.
Are your text files a letter type form or just columns of data that is fixed length?
If you can provide a few lines of the incoming data I might be able to show you some ways to break the data down and send it on to where it needs to go.


Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
code conversion from excel vba to visual basic for visual studio 5 49
DataGridView Events ? 3 45
Help with LINQ and XML 10 36
write xml in 2 24
Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question