views:

4629

answers:

4

Hi all,

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

+3  A: 
[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");
}
marcumka
+5  A: 

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();
Kyralessa
excellent, thanks!
Max Schilling
+1  A: 

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.

Michael Meadows
WTF? If you're going to downvote this, at least give an explanation. The information presented is absolutely true.
Michael Meadows
Please do more research if you are not sure... remember something?
Daok
A revenge downvote, nice.Please substantiate what you think isn't correct about what I stated.
Michael Meadows
Error is human, the link I provided had 3.5 in bold and 2.0 in normal, I haven't see it. I have deleted my post... a simple comment from you would have been enough. You want to downvote for no reason, than now assume.
Daok
I have never downvoted anyone for anything. If I do, it will be because it is sitting higher on the stack than better answers. I'm still challenging you to substantiate what's wrong with my answer in this post.
Michael Meadows
Although I am writing this almost a year later, and although I am not Daok, I will tell you why your answer is "wrong" - you said "Kyralessa's solution is your best option" when it isn't - my solution is cleaner and clearer.
Jason Bunting
+12  A: 

Easiest approach:

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

Not too much different than your example code - just a re-assignment and different extension method.

Jason Bunting
I have to agree with you Jason, this is more in line with what I was looking for.
Max Schilling