How to convert all strings in List <string> to lowercase using LINQ?

Yesterday, I saw a piece of code in one of the answers here on StackOverflow that intrigued me. It was something like this:

List<string> myList = new List<string> {"aBc", "HELLO", "GoodBye"}; myList.ForEach(d=>d.ToLower()); 

I was hoping I could use it to convert all the elements in myList to lowercase. However, this does not happen ... after doing this, the wrapper in myList has not changed.

So my question is, is there a way, using LINQ and Lambda expressions, to easily iterate and modify the contents of a list in a similar way.

Thanks Max

+73
c # lambda foreach linq
Oct 23 '08 at 18:54
source share
5 answers

The easiest approach:

 myList = myList.ConvertAll(d => d.ToLower()); 

Not too different from the code in your example. ForEach completes the original list, while ConvertAll creates a new one that needs to be reassigned.

+127
Oct 23 '08 at 19:05
source share

This is because ToLower returns a string string instead of converting the original string. So you need something like this:

 List<string> lowerCase = myList.Select(x => x.ToLower()).ToList(); 
+34
Oct 23 '08 at 19:00
source share
 [TestMethod] public void LinqStringTest() { List<string> myList = new List<string> { "aBc", "HELLO", "GoodBye" }; myList = (from s in myList select s.ToLower()).ToList(); Assert.AreEqual(myList[0], "abc"); Assert.AreEqual(myList[1], "hello"); Assert.AreEqual(myList[2], "goodbye"); } 
+3
Oct 23 '08 at 19:00
source share

ForEach uses Action<T> , which means you can affect x if it hasn't been immutable. Since x is a string , it is immutable, so you do nothing with it in lambda, change its properties. The Kyralessa solution is your best option if you do not want to implement your own extension method that allows you to return a replacement value.

+3
Oct 23 '08 at 19:05
source share
 var _reps = new List(); // with variant data _reps.ConvertAll<string>(new Converter<string,string>(delegate(string str){str = str.ToLower(); return str;})).Contains("invisible")) 
-one
Mar 07 '13 at 8:13
source share



All Articles