C# 枚举字母表的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2208688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:26:53  来源:igfitidea点击:

Quickest way to enumerate the alphabet

c#alphabet

提问by Ben Aston

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"

编辑:该指标是“最少要实现,同时仍具有可读性和健壮性”

采纳答案by Richard Szalay

(Assumes ASCII, etc)

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

回答by Bobby

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.

虽然,也不是最好的方法。如果我们知道这样做的原因,也许我们可以提供更好的帮助。

回答by Colin Newell

Or you could do,

或者你可以这样做

string alphabet = "abcdefghijklmnopqrstuvwxyz";

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

回答by Chris

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.

在随机阅读此博客时,认为这是完成任务的一种有趣方式。

回答by John Boker

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

回答by shankar.siva

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

回答by Martin Prikryl

Use Enumerable.Range:

使用Enumerable.Range

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