Ben Aston Ben Aston - 7 days ago 6
C# Question

Quickest way to enumerate the alphabet

I want to iterate over the alphabet like so:

foreach(char c in alphabet)
{
//do something with letter
}


Is an array of chars the best way to do this? (feels hacky)

Edit: The metric is "least typing to implement whilst still being readable and robust"

Answer

(Assumes ASCII, etc)

for (char c = 'A'; c <= 'Z'; c++)
{
    //do something with letter 
} 

Alternatively, you could split it out to a provider and use an iterator (if you're planning on supporting internationalisation):

public class EnglishAlphabetProvider : IAlphabetProvider
{
    public IEnumerable<char> GetAlphabet()
    {
        for (char c = 'A'; c <= 'Z'; c++)
        {
            yield return c;
        } 
    }
}

IAlphabetProvider provider = new EnglishAlphabetProvider();

foreach (char c in provider.GetAlphabet())
{
    //do something with letter 
} 
Comments