Reputation: 2571
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 definied 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.
Upvotes: 1
Views: 940
Reputation: 36
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'
Upvotes: 0
Reputation: 81660
Solution 1 - Super fast but unsafe:
[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.fixed
blockIntPtr
and use Marshal.PtrToStructure()
to load an onject of your classSolution 2 - Loading logic in the class:
byte[]
and inside the objects using Covenrt.Toxxx
or Encoding.ASCII.ToString()
assuming it is ASCIIbyte[]
then implement a ToByteArray() method and again use Covenrt.Toxxx
or Encoding.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.
Upvotes: 1
Reputation: 29401
Use a StringReader to parse your text, then you won't have to use substring. Linq won't help you here.
Upvotes: 0