I got a flat file where the data is not delimetered or something else. The file contains one large string and one row is represented by 180 chars.
Each column value is defini开发者_如何学Pythoned by a length of chars. I have to create an object for each row, parse the 180 chars and fill properties of the created object with the parsed values.
How can i solve this problem without permanent using substring or something else?
Maybe some nice solution with Linq?
Thanks a lot.
Solution 1 - Super fast but unsafe:
- Create your class with
[StructLayout(LayoutKind.Sequential)]
and all other unmanaged code markings for length. Your strings will be char array but can be exposed as string after loading. - Read 180 bytes and create a byte array of the same size inside a
fixed
block - Change pointer to
IntPtr
and useMarshal.PtrToStructure()
to load an onject of your class
Solution 2 - Loading logic in the class:
- Create a constructor in your class that accepts
byte[]
and inside the objects usingCovenrt.Toxxx
orEncoding.ASCII.ToString()
assuming it is ASCII - Read 180 bytes and create an object and pass it to .ctor
- If you have to serialise back to
byte[]
then implement a ToByteArray() method and again useCovenrt.Toxxx
orEncoding.ASCII.ToString()
to write to byte.
Enhancement to solutions 2:
Create custom attributes and decorate your classes with those so that you can have a factory that reads metadata and inflates your objects using byte array for you. This is most useful if you have more than a couple of such classes.
Alternative to solutions 2:
You may pass stream instead of a byte array which is faster. Here you would use BinaryReader and BinaryWriter to read and write values. Strings however is a bit trick since it writes the length as well I think.
Use a StringReader to parse your text, then you won't have to use substring. Linq won't help you here.
I agree with OJ but even with StringReader you will still need the position of each individual value to parse it out of the string...there is nothing wrong with substring just make sure you use static constants when defining the begging and ending lengths. Example:
private static int VAR_START_INDEX = 0;
private static int VAR_END_INDEX = 4;
String data = "thisisthedata";
String var = data.Substring(VAR_START_INDEX,VAR_END_INDEX);
//var would then be equal to 'this'
This library can help you http://f2enum.codeplex.com/
精彩评论