c# - Arg assigning using for-switch -
so i'm writing programme reads in parameters config file.
i know read them array, assign each variable corresponding element array. thought, why not assign them read them in, know order read in beforehand. set switch in loop , assigned each variable based on index read in, simplified version shown below.
private void parsefile(string filename) { string line; system.io.streamreader file = new system.io.streamreader( filename ); (int = 0; (line = file.readline()) != null; ) { line = line.trim(); //comments made surrounding string in [] if (line[0] == '[' && line[line.length - 1] == ']') { continue; } switch (i) { case 0: firstvar = line; break; case 1: secondvar = line; break; case 2: thirdvar = line; break; default: throw new missingfieldexception( "error in construction of file variable " + line ); } ++i; } }
after writing out, however, looked ugly, , thought there must improve way.
my questions are:
is there improve way? if so, it? if not, preferable read array , assign over, or utilize for-switch construction , why?thanks in advance!
instead of declaring 3 separate variables each line store them in list
or array.
you can using linq easily:
var lines = file.readlines("path") .where(line => !line.startswith("[") && !line.endswith("]")) .tolist();
if still need assign each line separate variables can still it:
if(lines.count >= 3) { var firstvar = lines[0]; var secondvar = lines[1]; var thirdvar = lines[2]; }
c# arrays arguments switch-statement
No comments:
Post a Comment