Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to .ToUpper() each element of an array using LINQ?

Tags:

c#

linq

.net-4.0

I have this LINQ expression:

string[] x = originalString.Split(',').ToList().ForEach(y => y.Substring(0,1).ToUpper());

I'm getting this error message:

Cannot convert source type 'void' to target type 'string[]'

I think I get the error; The ForEach returns void. I'm not sure how to fix it and still keep this a LINQ expression.

How do I split originalString and then loop over the elements in the array, applying .ToUpper() on each element AND do it all in a LINQ expression?

like image 247
DenaliHardtail Avatar asked Mar 11 '13 17:03

DenaliHardtail


1 Answers

string[] x = originalString.Split(',')
                           .Select(y => y.Substring(0,1).ToUpper())
                           .ToArray();

Should do the thing - get the first letter of each word, uppercase.

But I think what you're really looking for is:

string[] x = originalString.Split(',')
                           .Select(y => y.Substring(0, 1).ToUpper() + y.Substring(1))
                           .ToArray();

That should capitalize elements which were split from input (sounds much more useful).

Example of usage for second query:

 string originalString = "TestWord,another,Test,word,World,Any";

Output:

TestWord
Another
Test
Word
World
Any
like image 107
MarcinJuraszek Avatar answered Sep 23 '22 01:09

MarcinJuraszek