Convert Structure to String in VB.Net

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

I am in the process of converting a VB6 program to vb.net.  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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 1000 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 & item.name)
    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.
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

650 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