David.Chu.ca
David.Chu.ca

Reputation: 38654

C# codes to get a list of strings like A to Z?

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?

Upvotes: 4

Views: 9955

Answers (8)

Marcin Deptuła
Marcin Deptuła

Reputation: 11957

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) + ":");

Upvotes: 4

Lester
Lester

Reputation: 513

Other answer ;-)

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

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170745

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

Upvotes: 0

Sam Harwell
Sam Harwell

Reputation: 99889

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() + ':'));

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500835

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 + ":");
}

Upvotes: 12

Joe Chung
Joe Chung

Reputation: 12123

from ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" select ch + ":";

Upvotes: 14

JP Alioto
JP Alioto

Reputation: 45117

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).

Upvotes: 0

waterlooalex
waterlooalex

Reputation: 13892

How about:

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

Upvotes: 1

Related Questions