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.
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

820 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