A-list from char from Enumerable.Range

I want to create 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?

Thanks in advance:)

+8
c # linq
source share
3 answers

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

 "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToList() 

You must weigh the pros and cons.

Pros:

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

Minuses:

  • It is harder to read if you do not know what .ToList() will do with the string
  • You can enter errors, for example, you would easily notice an error here:

     "ABCDEFGHIJKLMN0PQRSTUVWXYZ".ToList() 

    I easily mean that you noticed an error, because you are just reading the code, and not if you know that there is a problem here and went in search of.

+15
source share

Maybe so?

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

I took the 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); } 

Using:

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

All Articles