列举字母表的最快方法

我想像这样迭代字母表:

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

字符数组是做到这一点的最好方法吗? (感觉很古怪)

编辑: 度量标准是“在保持可读性和健壮性的同时实现的类型最少”

81523 次浏览

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

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.

Or you could do,

string alphabet = "abcdefghijklmnopqrstuvwxyz";


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

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.

Enumerable.Range(65, 26).Select(a => new { A = (char)(a) }).ToList().ForEach(c => Console.WriteLine(c.A));
var alphabet = Enumerable.Range(0, 26).Select(i => Convert.ToChar('A' + i));

Use Enumerable.Range:

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