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!

Filed under: , , ,

Comments

# re: Building a Set of Alphabetic Letters

Monday, February 22, 2010 4:45 PM by Nate Oliver

Nice! When you say VB, let's be sure it's understood we're looking at VB.Net. As an Office user, there's a difference, Office still uses legacy VB6'ish.

# re: Building a Set of Alphabetic Letters

Monday, February 22, 2010 5:15 PM by Deborah Kurata

Hi Nate -

Thank you for your comment. The VB that is in Office is called "VBA". The *official* name of the VB that is part of .NET is "Visual Basic", which I abbreviate VB.

Hope this clears things up.

# re: Building a Set of Alphabetic Letters

Monday, February 22, 2010 5:58 PM by Nate Oliver

I understand completely, just by reading your post. Just noting that VBA is actually a superset of VB6 - and still in play.

Cheers, Nate

Microsoft Excel MVP

# re: Building a Set of Alphabetic Letters

Monday, February 22, 2010 6:33 PM by Nate Oliver

If you were using a VB6-type environment, which includes VBA, I'd use a Byte Array. E.g.,

www.xtremevbtalk.com/showpost.php

That does hardcode, but assumes you know which chars you want. And it's blazing fast.

Cheers, Nate

# re: Building a Set of Alphabetic Letters

Monday, November 14, 2011 1:16 AM by Matt Penner

Awesome!  Thanks.  Definitely a nice little set of code. ;)

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: