Quickest way to enumerate the alphabet

后端 未结 7 666
猫巷女王i
猫巷女王i 2020-11-29 02:15

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

相关标签:
7条回答
  • 2020-11-29 02:35

    (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 
    } 
    
    0 讨论(0)
  • 2020-11-29 02:35
    var alphabet = Enumerable.Range(0, 26).Select(i => Convert.ToChar('A' + i));
    
    0 讨论(0)
  • 2020-11-29 02:42
    Enumerable.Range(65, 26).Select(a => new { A = (char)(a) }).ToList().ForEach(c => Console.WriteLine(c.A));
    
    0 讨论(0)
  • 2020-11-29 02:45

    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.

    0 讨论(0)
  • 2020-11-29 02:47

    Or you could do,

    string alphabet = "abcdefghijklmnopqrstuvwxyz";
    
    foreach(char c in alphabet)
    {
     //do something with letter
    }
    
    0 讨论(0)
  • 2020-11-29 02:47

    Use Enumerable.Range:

    Enumerable.Range('A', ('Z' - 'A' + 1)).Select(i => (char)i)
    
    0 讨论(0)
提交回复
热议问题