How do you do a "ToUpper" on all char in a list in a single line in C#?

700 Views Asked by At

I was tasked with this assignement but I cannot figure out how to do it. I have a list of characters and I have to return a new list with the same contents except all the characters that are lowercase are changed to uppercases.

2

There are 2 best solutions below

0
On

i recommend reading this article, it simply says that you have to check if the char case is lower and then make it upper using the following code

string str1="Great Power";  
        char ch;  
        System.Text.StringBuilder str2 = new System.Text.StringBuilder();  

for(int i = 0; i < str1.Length; i++) {  
            //Checks for lower case character  
            if(char.IsLower(str1[i])) {  
                //Convert it into upper case using ToUpper() function  
                ch = Char.ToUpper(str1[i]);  
                //Append that character to new character  
                str2.Append(ch);  
            }
2
On

I assume you mean you have a List<char> and want all entries uppercased, use LINQ and lambda expressions.

var chars = new List<char> {'a', 'b', 'c'};
var newList = chars.Select(Char.ToUpper).ToList();

Select invokes Char.ToUpper() on all entries and ToList() converts the result back to a list.