Convert Structure to String in VB.Net

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.

Who is Participating?
GohdanTheMoblinConnect With a Mentor Commented:
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.
Some code would be nice...

There is ways to use structures as string arrays, but need more info from you.
GeneMAuthor Commented:
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.
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

How is your data coming into you? A text file, a database?
GeneMAuthor Commented:
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.

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?
GeneMAuthor Commented:
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.


"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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.