vb.net - How to split string, apply function to every part and rejoin back without loops in .NET? -
i perform these actions inside single evaluation, if possible:
- split string
inputparts according separatorseparator - apply function
fnc(string) -> stringevery part - rejoin parts string
resultusing same separatorseparator
that's all.
the best figure out (this in vb)
result = input.split(separator).aggregate(string.empty, function(result, part) _ result & if(result = string.empty, string.empty, separator) & fnc(part)) as can see, ugly because
aggregate()needs initialization in 1st parameter (ifaggregate()used without first parameter, doesn't callfnc()1st element of array)this approach forces
if()usage, otherwiseseparatoradded start of result
i experimented using select() , selectmany() on array created through split(), when apply string.join() on result, i'm getting cast error(!) during runtime (build works ok) , not understand why.
here effective form crashes during runtime:
result = string.join(separator, input.split(separator).selectmany(function(part) fnc(part))) with exception:
system.invalidcastexception: unable cast object of type 'd__14`2[system.string,system.char]' type 'system.string[]'.
could please suggest better approach evaluation? if can select() , selectmany() made working string.join()... or there other effective way?
feel free respond in vb or c#.
edit: how can done, not how readable such code might someone. lambda expressions used here alien many programmers. know how classic approach problem looks - foreach helper variables around...
after additional thinking , trying i've found out simple solution exists:
result = string.join(separator, input.split(separator).select( function(part) fnc(part)).toarray()) clean , effective!
so select() approach mentioned in question way working result. adding toarray() result did trick.
thank effort!
Comments
Post a Comment