枚举在C#字母表最快的方法
问题描述:
我要遍历像这样的字母:
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)
编辑:指标是至少打字来实现,同时仍具有可读性和强大的
The metric is "least typing to implement whilst still being readable and robust"
答
(假设ASCII等)
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
}