Quickest way to enumerate the alphabet

Ben Aston picture Ben Aston · Feb 5, 2010 · Viewed 73k times · Source

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

Richard Szalay picture Richard Szalay · Feb 5, 2010

(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 
}