Quickest way to enumerate the alphabet

2019-01-06 13:06发布

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# alphabet
8条回答
We Are One
2楼-- · 2019-01-06 13:31
Enumerable.Range(65, 26).Select(a => new { A = (char)(a) }).ToList().ForEach(c => Console.WriteLine(c.A));
查看更多
叛逆
3楼-- · 2019-01-06 13:34

(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 
} 
查看更多
聊天终结者
4楼-- · 2019-01-06 13:50
var alphabet = Enumerable.Range(0, 26).Select(i => Convert.ToChar('A' + i));
查看更多
做自己的国王
5楼-- · 2019-01-06 13:52

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.

查看更多
做自己的国王
6楼-- · 2019-01-06 13:53

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.

查看更多
狗以群分
7楼-- · 2019-01-06 13:54

Or you could do,

string alphabet = "abcdefghijklmnopqrstuvwxyz";

foreach(char c in alphabet)
{
 //do something with letter
}
查看更多
登录 后发表回答