The fastest way to list the alphabet

I want to iterate alphabetically like this:

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

Is an array of characters the best way to do this? (feels hacked)

Edit: the metric is "the least typed for implementation, although it is still readable and reliable"

+50
c #
05 Feb '10 at 16:37
source share
7 answers

(implies ASCII, etc.)

 for (char c = 'A'; c <= 'Z'; c++) { //do something with letter } 

Alternatively, you can split it into a provider and use an iterator (if you plan to support internationalization):

 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 } 
+120
Feb 05 '10 at 16:40
source share

Or you could do

 string alphabet = "abcdefghijklmnopqrstuvwxyz"; foreach(char c in alphabet) { //do something with letter } 
+31
Feb 05 '10 at 16:42
source share
 var alphabet = Enumerable.Range(0, 26).Select(i => Convert.ToChar('A' + i)); 
+5
May 03 '16 at 10:25
source share
 Enumerable.Range(65, 26).Select(a => new { A = (char)(a) }).ToList().ForEach(c => Console.WriteLine(cA)); 
+3
Feb 09 '10 at 22:57
source share

It's good to use a foreach in C #, the alphabet can be any IEnumerable<char> . What feels "hacked"?

+2
Feb 05 '10 at 16:41
source share

You can do it:

 for(int i = 65; i <= 95; i++) { //use System.Convert.ToChar() fe here doSomethingWithTheChar(Convert.ToChar(i)); } 

Although, this is not the best way. Maybe we could help better if we knew the reason for this.

+1
Feb 05 '10 at 16:40
source share

I found this:

 foreach(char letter in Enumerable.Range(65, 26).ToList().ConvertAll(delegate(int value) { return (char)value; })) { //breakpoint here to confirm } 

while accidentally reading this blog and thought it was an interesting way to complete the task.

0
Feb 09 2018-10-09T00
source share



All Articles