views:

423

answers:

8

How can I get a list of strings from "A:" to "Z:" in C#? Something like this:

List<string> list = new List<string>();
for (int i = 0; i < 26; i++)
{
   list.Add(string.Format("{0}:", Convert.ToChar('A' + i));
}

Sorry I don't have VS available for verification right now to verify. By the way, is there web site available to interactive test snip of codes?

+10  A: 

Using LINQ:

List<string> aToZ = Enumerable.Range('A', 26)
                              .Select(x => (char) x + ":")
                              .ToList();

Not using LINQ - a simpler alternative (IMO) to the original for loop:

List<string> list = new List<string>();
for (char c = 'A'; c <= 'Z'; c++)
{
   list.Add(c + ":");
}
Jon Skeet
Heh, you used lowercase letters though! (just kidding, we have almost identical answers)
280Z28
Oops, thanks, fixed :)
Jon Skeet
You English guys are lucky to have an alphabet that comes in sequence ;o)
Fredrik Mörk
+2  A: 

Edit: Y'all should have marked me down for replying without reading. This doesn't work in VS2005, which is what the OP asked about.

List<string> list = new List<string>(Enumerable.Range((int)'A', 26).Select(value => ((char)value).ToString() + ':'));
280Z28
No need to explicitly call ToString you use a string literal on the RHS of the +. Or there's string.Format of course.
Jon Skeet
Since it no longer applies, you can delete it.
John Saunders
It doesn't apply for the OP, but it applies to the title of the thread and perhaps other people perusing things. :)
280Z28
+1  A: 

How about:

var list = Enumerable.Range('a', 'z' - 'a' + 1).Select(charCode => (char)charCode)).ToList();
Alex Black
A: 

Yours works fine with the exception of missing a ). I test all my snipits with LinqPad. (I don't know how I ever lived without it).

JP Alioto
+2  A: 

Well, not counting missing ')' at the end of list.Ad.... line, everything is ok, altough you could write it using a bit shorter notation
list.Add((char)('A' + i) + ":");

Ravadre
I like this. It should work in both VS 2005 and 2008
David.Chu.ca
That's a lot of unnecessary casting etc though - see my revised solution if you're not keen on LINQ.
Jon Skeet
+11  A: 
from ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" select ch + ":";
Joe Chung
I really like the look of this one.
Jamie Penney
Yup, that's sweet.
Jon Skeet
Alternatively: "ABCDEFGHIJKLMNOPQRSTUVWXYZ".Select(ch => ch + ":") - same thing, no need for "from" or "in".
Jon Skeet
That is a nice one; works also for ranges that do not come in sequence, such as the Swedish alphabet.
Fredrik Mörk
A: 

Other answer ;-)

List list = new List(); for (int i = 'A'; i <= 'Z'; i++) { list.Add(string.Format("{0}:", Convert.ToChar(i))); }

Lester
A: 

For testing code snippets, I use LinqPad or Snippet Compiler. I prefer LinqPad but both are very nice.

Alexey Romanov