user196546
user196546

Reputation: 2593

C# Enumerable Range

What is the way to get Range "A"..."Z" like

Enumerable.Range(1,100) 

Enumerable.Range("A","Z");

Upvotes: 7

Views: 5524

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500695

EDIT: Updated to include Darin's correction...

In .NET 3.5 SP1, this would have worked:

Enumerable.Range('A', 26).Cast<char>()

However, the behaviour of Cast changed for .NET 3.5 SP1, so it now only performs reference conversions on unboxing conversions. So for .NET 3.5SP1 and above, you need:

Enumerable.Range('A', 26).Select(x => (char) x);

It's not terribly nice, admittedly.

With MiscUtil you could use

'A'.To('Z').StepChar(1)

Whether you like that or not is a matter of personal taste :)

Upvotes: 13

gprasant
gprasant

Reputation: 16023

Another method, if you want to slice from one element of the alphabet to another...

Enumerable.Range(0,26).Select(x => (char)((char)x + 'A'))

Upvotes: 1

James
James

Reputation: 82096

Why not just keep it simple...

public static IEnumerable<char> GetAlphabet()
{
    return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".AsEnumerable();
}

Upvotes: 12

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

Enumerable.Range('A', 26).Select(x => ((char)x).ToString())

Upvotes: 10

Related Questions