-1

I would like to do the same thing as this Python function but in C#.
Ideally in a one-line like in Python.

def to_classname(name: str) -> str:
    """
    something-2do -> Something2do
    firefox-developer -> FirefoxDeveloper
    """
    return ''.join([x.capitalize() for x in name.split('-')])
0lan
  • 179
  • 1
  • 14
  • Why do you need to convert? Python converts the classes to strings. In c# there is not reason to convert to strings. So you do not need the function. – jdweng Jun 22 '20 at 12:30
  • 2
    `string.Concat(name.Split('-').Select(x => char.ToUpper(x[0]) + x.Substring(1));` – juharr Jun 22 '20 at 12:37

2 Answers2

1

You can use the following. It splits the string on the hyphen and removes any empty strings (due to multiple consecutive hyphens). It then joins the entries, after mapping each one to a string where the first letter is uppercase and the remainder is lower.

public static string ToClassName(string str)
{
   var splits = str.Split('-', StringSplitOptions.RemoveEmptyEntries);
   return string.Concat(splits.Select(s => char.ToUpper(s[0]) + (s.Length > 1 ? s.Substring(1).ToLower() : "")));
}

You may need to add the following:

using System.Linq;

Note that it does not validate the input which is trivial.

pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
0

Based on this answer, I am proposing this solution.

using System;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var rawName = "firefox-developer";
        string className=string.Empty;
        rawName.Split('-').ToList().ForEach(name => className += (name.First().ToString().ToUpper() + name.Substring(1)));
        System.Console.WriteLine(className);
    }
}
Sathish Guru V
  • 1,417
  • 2
  • 15
  • 39