I am kinda new to C# and am doing random things; One of which requires this:
The “1” turning into “one” is just an example, they will just be 1 word into another, but I need to do this upwards of 50 times. Is there a way to do it either more compactly or easier?
I feel like a dictionary data structure may be more appropriate here. That way, you can just map the numbers to their written forms.
I hope this makes since. A dictionary data structure is used to map values to others. In this example, you want numerical values to be mapped to their names, so you can write it to the console. This way, you can just check if a number exists in the dictionary instead of checking every value.
What are your thoughts on a switch instead of a dictionary?
Humanizer can do this if you need to support arbitrary input values, though it may not be your exact use-case if your input is strings and not numerical values.
You could in theory parse to a number type then run it through Humanizer but it probably depends how pre-defined the inputs are, otherwise a Dictionary may be easier as others have mentioned.
There are a couple ways, but perhaps the most straightforward way is to move the conversion work into a method, then maybe use a switch:
And your foreach
loop would look like:
There are more compact ways, perhaps with a Dictionary<string, string>
lookup, but this might be a good starting point.
EDIT: If you are using a recent version of C# with the C# 8 features, you can use the new “switch expression” language feature:
string [] numbers =[“zero”, “one”, “two”…];
Damn everyone suggesting switch statements totally missed this obvious answer. I missed it, too
https://github.com/Humanizr/Humanizer is brilliant for this kind of thing.
A different approach.
At a minimum you need to associate a string to another unrelated string. At the bare minimum this can be represented by the hypothetical structure string=other string A collection of these could be represented by pair1npair2n
You can’t get any smaller.
Then you have your mapping function. If tests. Case statements. Dictionaries. It doesn’t matter if your if test or case is a statement or an expression. (If else vs ?:) it’s still code you have to maintain. The only mapping function you don’t have to maintain is Dictionary.
It’s all declarative data driven code with logic safely and correctly applied by standard library code that you don’t have to maintain.
what about using switch?
Enums?
A switch statement as mentioned. Also what’s the point of using string interpolation in the final clause if you’re not adding anything to the string?
He may not know that you can just print the string, we were all there at some point
Use Switch statement. Then you just use case 1, case 2, case 3 etc.
https://www.c-sharpcorner.com/article/convert-numeric-value-into-words-currency-in-c-sharp/
If only C# had advanced pattern matching like in Rust… It would replace switch.
source