开发者

How to convert array to string and vice versa?

How to convert a array <-> string?

I've a bi dimensional array 开发者_C百科and i need to save to database and retrieve.

Dim myarray(,) as string = {{"some","some"},{"some","some"}}


Although XmlSerializer cannot serialize multi-dimentional arrays (String(,)), itcan serialize jagged arrays (String()()). So, if you are willing to use an "array of array of strings" instead of a "two-dimensional array of string", you can use the XmlSerializer.

Example of how to serialize (imports System.Xml.Serialization and System.IO):

    Dim myarray()() As String = { _
        New String() {"some", "some"}, _
        New String() {"some", "some"}}

    Dim s As New XmlSerializer(GetType(String()()))
    Dim stream As New StringWriter()
    s.Serialize(stream, myarray)

    Dim myString = stream.ToString()

myString then contains:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ArrayOfString>
    <string>some</string>
    <string>some</string>
  </ArrayOfString>
  <ArrayOfString>
    <string>some</string>
    <string>some</string>
  </ArrayOfString>
</ArrayOfArrayOfString>

Likewise, to deserialize, you can use s.Deserialize.


You could use a StringBuilder and iterate through the array using a marker of some sort, such as a semi-colon to indicate the pairs and a dash to indicate the string in the pair i.e. some-some, and write out the StringBuilder.ToString() i.e. some-some;some-some to the database. Then when you read from the database a string in this fashion and simply rebuild the array by using the markers to separate out the elements from the string itself.

Hope this helps, Best regards, Tom.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜