Question:
I would like to know how I can convert a string with CamelCase to snake_case in C#.
For example:
EuAmoCsharp => eu_amo_csharp
SnakeCase => snake_case
Answer:
It would be something like this:
string stringSnake = string.Concat(
stringCamel.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString().ToLower() : x.ToString().ToLower())
);
Explaining:
string
is an enumeration of char
in C#. So I can use:
stringCamel.Select()
One way to use Select
is to specify two variables in the predicate, where x
the current character of the iteration and i
the index of that iteration.
The conditional is simpler to understand:
i > 0 && char.IsUpper(x) ? "_" + x.ToString().ToLower() : x.ToString().ToLower()
I check if i
is greater than zero and if the current character is uppercase, because I don't want to write _
before the first character.
If the character is uppercase, I write _
and the character in lowercase. Otherwise I just write the character.
I need to keep ToLower()
on both results because of the first character.