c# - Throwing exceptions from Linq Query exception -
lets have input string need format list of keyvaluepair<string,float>
entries. format of input string
key:value;key:value;...
lets have linq code it
var orr = pco in (overrrides ?? string.empty).split(new char[] { ';' }, stringsplitoptions.removeemptyentries) let pair = pco.split(new char[] { ':' }, stringsplitoptions.removeemptyentries) select new keyvaluepair<string, float>(pair[0], float.parse(pair[1]));
now, if input string not formated linq fail on 2 possible points, index out of range on pair[]
, format exception on float.parse
. both of these exceptions bobble , mean absolutely nothing caller.
i know have 2 workarounds (not use linq , loop 1990s or grab above exceptions , repackage), wondering if can somehow inject validation steps linq query throw own exceptions if detect anomaly (pair.length<2
or pair[1]
not number)?
one simple option change to:
// don't think i'd use ?? this, that's not point of question. var unparsed = (overrrides ?? string.empty).split(new char[] { ';' }, stringsplitoptions.removeemptyentries); var parsed = unparsed.select(x => parsepair(x)); ... static keyvaluepair<string, float> parsepair(string text) { // note more efficient using indexof/substring string[] bits = text.split(new char[] { ':' }, stringsplitoptions.removeemptyentries); if (bits.length != 2) { throw new argumentexception("value should colon-separated key/float pair"); } float value; if (!float.tryparse(bits[1], out value)) { throw new argumentexception("cannot parse " + bits[1] + " float"); } return new keyvaluepair<string, float>(bits[0], value); }
you're still using linq "sequence" part - you're breaking "how handle single value" part separate method. (you could big statement lambda, wouldn't.) note doing so, test parsepair
method independently.
(you might away .select(parsepair)
, depending on version of c# you're using. method group conversions , type inference aren't best of friends though.)
Comments
Post a Comment