Max Schilling
Max Schilling

Reputation: 2921

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

I saw a code snippet yesterday in one of the responses 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 items in myList to lowercase. However, it doesn't happen... after running this, the casing in myList is unchanged.

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

Thanks, Max

Upvotes: 116

Views: 131435

Answers (5)

Jason Bunting
Jason Bunting

Reputation: 58931

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.

Upvotes: 225

Uhlamurile
Uhlamurile

Reputation: 29

var _reps = new List(); // with variant data

_reps.ConvertAll<string>(new Converter<string,string>(delegate(string str){str = str.ToLower(); return str;})).Contains("invisible"))

Upvotes: -1

Michael Meadows
Michael Meadows

Reputation: 28416

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.

Upvotes: 5

Ryan Lundy
Ryan Lundy

Reputation: 210140

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();

Upvotes: 57

marcumka
marcumka

Reputation: 1695

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

Upvotes: 4

Related Questions