C# 如何使用 LINQ 将 List<string> 中的所有字符串转换为小写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/230973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Convert all strings in List<string> to lower case using LINQ?
提问by Max Schilling
I saw a code snippet yesterday in one of the responses here on StackOverflow that intrigued me. It was something like this:
昨天我在 StackOverflow 上的一个回复中看到了一段代码片段,这让我很感兴趣。它是这样的:
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.
我希望我可以用它来将 myList 中的所有项目转换为小写。但是,它不会发生……运行此命令后, myList 中的大小写不变。
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.
所以我的问题是是否有一种方法,使用 LINQ 和 Lambda 表达式以类似于此的方式轻松迭代和修改列表的内容。
Thanks, Max
谢谢,马克斯
采纳答案by Jason Bunting
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.
与您的示例代码没有太大不同。ForEach
循环原始列表,同时ConvertAll
创建一个您需要重新分配的新列表。
回答by marcumka
[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");
}
回答by Ryan Lundy
That's because ToLower returnsa lowercase string rather than converting the original string. So you'd want something like this:
这是因为 ToLower返回小写字符串而不是转换原始字符串。所以你会想要这样的东西:
List<string> lowerCase = myList.Select(x => x.ToLower()).ToList();
回答by Michael Meadows
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.
ForEach
uses Action<T>
,这意味着x
如果它不是不可变的,你可能会影响。由于x
is a string
,它是不可变的,所以你在 lambda 中对它做的任何事情都不会改变它的属性。Kyralessa 的解决方案是您的最佳选择,除非您想实现自己的扩展方法,允许您返回替换值。
回答by Uhlamurile
var _reps = new List(); // with variant data
_reps.ConvertAll<string>(new Converter<string,string>(delegate(string str){str = str.ToLower(); return str;})).Contains("invisible"))