Solved

Convert Structure to String in VB.Net

Posted on 2004-10-19
8
2,177 Views
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.

0
Comment
Question by:GeneM
  • 3
  • 3
  • 2
8 Comments
 
LVL 27

Expert Comment

by:planocz
Comment Utility
Some code would be nice...

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

Accepted Solution

by:
GohdanTheMoblin earned 250 total points
Comment Utility
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:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemicomparableclasstopic.asp

CompareTo method:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemicomparableclasscomparetotopic.asp

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
        Else
            '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
        Next

        'Print initial values
        PrintArray(test)

        'sort the array
        Array.Sort(test)

        'Print the sorted array
        PrintArray(test)

        Console.ReadLine()
    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)
        Next
    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.
0
 
LVL 3

Author Comment

by:GeneM
Comment Utility
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
           etc.

        ReDim Preserve DetDataArray(n) As String
        DetDataArray(n) = Space$(Len(detdata))
        CopyMemory ByVal DetDataArray(n), detdata, Len(detdata)
        n = n + 1
    Loop
            
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.
0
 
LVL 27

Expert Comment

by:planocz
Comment Utility
How is your data coming into you? A text file, a database?
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 3

Author Comment

by:GeneM
Comment Utility
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.

GeneM
0
 
LVL 2

Expert Comment

by:GohdanTheMoblin
Comment Utility
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?
0
 
LVL 3

Author Comment

by:GeneM
Comment Utility
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.

GeneM

0
 
LVL 27

Expert Comment

by:planocz
Comment Utility
"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.

0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now