How to Convert all strings in List<string> to lower case using LINQ?

Solution 1:

Easiest approach:

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

Not too much different than your example code. ForEach loops the original list whereas ConvertAll creates a new one which you need to reassign.

Solution 2:

That's because ToLower returns a lowercase string rather than converting the original string. So you'd want something like this:

List<string> lowerCase = myList.Select(x => x.ToLower()).ToList();

Solution 3:

ForEach uses Action<T>, which means that you could affect x if it were not immutable. Since x is a string, it is immutable, so nothing you do to it in the lambda will change its properties. Kyralessa's solution is your best option unless you want to implement your own extension method that allows you to return a replacement value.

Solution 4:

[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");
}