Reputation: 38654
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
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
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
Reputation: 170745
For testing code snippets, I use LinqPad or Snippet Compiler. I prefer LinqPad but both are very nice.
Upvotes: 0
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
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
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
Reputation: 13892
How about:
var list = Enumerable.Range('a', 'z' - 'a' + 1).Select(charCode => (char)charCode)).ToList();
Upvotes: 1