如何使用 LINQ 将 List < string > 中的所有字符串转换为小写?

昨天我在 StackOverflow 的一个回复中看到了一个代码片段,这引起了我的兴趣。大概是这样的:

 List<string> myList = new List<string> {"aBc", "HELLO", "GoodBye"};


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

我希望可以用它来将 myList 中的所有项目转换为小写。但是,这种情况不会发生... ... 在运行这个命令之后,myList 中的大小写没有变化。

所以我的问题是,是否有一种方法,使用 LINQ 和 Lambda 表达式以类似的方式轻松地遍历和修改列表的内容。

谢谢, 麦克斯

116214 次浏览
[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");
}

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

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.

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.

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


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