简体   繁体   中英

A to Z list of char from Enumerable.Range

I want to make a list from Enumerable.Range. Is this code correct?

SurnameStartLetterList = new List<char>();
Enumerable.Range(65, 26).ToList().ForEach(character => SurnameStartLetterList.Add((char)character));

Or is there a better way to make this type of list?

Maybe like this?

var surnameList = Enumerable.Range('A', 'Z' - 'A' + 1).
                     Select(c => (char)c).ToList();

Well, string is IEnumerable<char> , so this would also work:

"ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToList()

You have to weigh the pros and cons on this.

Pros:

  • Easier to read the above code than your loop (subjective, this was my opinion)
  • Shorter code (but probably not enough to account for much)

Cons:

  • Harder to read if you don't know what .ToList() will do with a string
  • Can introduce bugs, for instance, would you easily spot the mistake here:

     "ABCDEFGHIJKLMN0PQRSTUVWXYZ".ToList() 

    By easily I mean that you would spot the mistake as you're just reading past the code, not if you knew there was a problem here and went hunting for it.

I took Can's answer and made an extension function:

public static IEnumerable<char> Range(char start, char end)
{
  return Enumerable.Range((int)start, (int)end - (int)start + 1).Select(i => (char)i);
}

Usage:

Console.WriteLine(Range('a', 'f').Contains("Vive La France!"[6]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM