Building a Set of Alphabetic Letters
Posted
Mon, Feb 22 2010 13:38
by
Deborah Kurata
There may be times you need to work with a set of alphabetic letters. Say you need to use "ABCDEFGHIJ" in your application. Now you could hard-code these in your application, but this post shows another technique for generating sets of letters.
In C#:
// Initialize an array with letters
// This one does A, B, ... J
char[] letters = Enumerable.Range(0, 10).Select(i =>
((char)('A' + i))).ToArray();
Console.WriteLine(new string(letters));
// This one does z, y, ... q
char[] letters2 = Enumerable.Range(0, 10).Select(i =>
((char)('z' - i))).ToArray();
Console.WriteLine(new string(letters2));
In VB:
' Initialize an array with letters
' This one does A, B, ... J
Dim letters() As Char = Enumerable.Range(0, 10).Select( _
Function(i) (Chr(Asc("A") + i))).ToArray()
Console.WriteLine(letters)
' This one does z, y, ... q
Dim letters2() As Char = Enumerable.Range(0, 10).Select( _
Function(i) (Chr(Asc("z") - i))).ToArray()
Console.WriteLine(letters2)
This code uses the Enumerable Range method to generate a range of values. It then uses the char letter character codes to build the list.
The Console.WriteLine uses one of the string constructors to convert the array of char to a string.
The result is:
ABCDEFGHIJ
zyxwvutsrq
Use this technique any time you need to work with a set of alphabetic letters in your application.
Enjoy!