Quickest way to enumerate the alphabet

C#Alphabet

C# Problem Overview


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"

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Or you could do,

string alphabet = "abcdefghijklmnopqrstuvwxyz";

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

Solution 3 - C#

var alphabet = Enumerable.Range(0, 26).Select(i => Convert.ToChar('A' + i));

Solution 4 - C#

Enumerable.Range(65, 26).Select(a => new { A = (char)(a) }).ToList().ForEach(c => Console.WriteLine(c.A));

Solution 5 - C#

Use Enumerable.Range:

Enumerable.Range('A', ('Z' - 'A' + 1)).Select(i => (char)i)

Solution 6 - C#

You could do this:

for(int i = 65; i <= 95; i++)
{
    //use System.Convert.ToChar() f.e. here
    doSomethingWithTheChar(Convert.ToChar(i));
}

Though, not the best way either. Maybe we could help better if we would know the reason for this.

Solution 7 - C#

I found this:

foreach(char letter in Enumerable.Range(65, 26).ToList().ConvertAll(delegate(int value) { return (char)value; }))
{
//breakpoint here to confirm
}

while randomly reading this blog, and thought it was an interesting way to accomplish the task.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen AstonView Question on Stackoverflow
Solution 1 - C#Richard SzalayView Answer on Stackoverflow
Solution 2 - C#Colin NewellView Answer on Stackoverflow
Solution 3 - C#shankar.sivaView Answer on Stackoverflow
Solution 4 - C#John BokerView Answer on Stackoverflow
Solution 5 - C#Martin PrikrylView Answer on Stackoverflow
Solution 6 - C#BobbyView Answer on Stackoverflow
Solution 7 - C#ChrisView Answer on Stackoverflow