Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

February 22, 2010

Building a Set of Alphabetic Letters

Filed under: C#,VB.NET @ 3:38 pm

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!

5 Comments

  1.   NateOliver — February 22, 2010 @ 4:45 pm    Reply

    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.

  2.   DeborahK — February 22, 2010 @ 5:15 pm    Reply

    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.

  3.   NateOliver — February 22, 2010 @ 5:58 pm    Reply

    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

  4.   NateOliver — February 22, 2010 @ 6:33 pm    Reply

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

    http://www.xtremevbtalk.com/showpost.php?p=1069150

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

    Cheers, Nate

  5.   Matt Penner — November 14, 2011 @ 1:16 am    Reply

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

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs