C# ForEach 以修剪字符串数组中的字符串值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14894503/
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
ForEach to Trim string values in string array
提问by David
I just wondered why this ForEach doesn't work and leaves the values with trailing whitespace.
我只是想知道为什么这个 ForEach 不起作用,并且会留下尾随空格的值。
string days = "Monday, Tuesday, Wednesday, Thursday, Friday";
string[] m_days = days.Split(',');
m_days.ToList().ForEach(d => { d = d.Trim(); } );
I know there are other ways of doing this so i don't need and answer there.
我知道还有其他方法可以做到这一点,所以我不需要在那里回答。
采纳答案by Tim Schmelter
Because you are not reassigning the trimmed strings.
因为您没有重新分配修剪后的字符串。
var list = m_days.Split(',').Select(s => s.Trim()).ToList();
Why
ForEach
doesn't work or if I am using theForEach
incorrectly?
为什么
ForEach
不起作用或者我使用ForEach
不正确?
ForEach
is not Linq, it's a method of List<T>
. What you are doing is basically this:
ForEach
不是 Linq,它是List<T>
. 你在做什么基本上是这样的:
foreach(string day in m_days)
{
day.Trim(); // you are throwing away the new string returned by String.Trim
}
Instead of using LINQ you could also use a for
-loop instead:
除了使用 LINQ,您还可以使用for
-loop 代替:
for(int i = 0; i < m_days.Length; i++)
{
m_days[i] = m_days[i].Trim();
}
回答by baldric
You need to assign the output of your ForEach to a new variable, like so:
您需要将 ForEach 的输出分配给一个新变量,如下所示:
var trimmedResult = m_days.Select(d => d.Trim()).ToList();
回答by Sergey Berezovskiy
Because String.Trim()
do not modify original string. When you call ForEach(d => d.Trim())
you create new trimmed string in memory for each item of list, but that string is not assigned anywhere. Thats what you are doing:
因为String.Trim()
不要修改原始字符串。当您调用时,ForEach(d => d.Trim())
您在内存中为列表的每个项目创建新的修剪字符串,但该字符串未分配给任何地方。这就是你在做什么:
foreach(string d in list)
{
d.Trim();
}
What you need is
你需要的是
m_days = days.Split(',').Select(d => d.Trim()).ToArray();
回答by Daniel Hilgarth
string.Trim
returns a new string instance. So you have to somehow usethat new instance.
You are not doing that in your code.
Furthermore, it is not possible with ForEach
. At first glance, the following could work:
string.Trim
返回一个新的字符串实例。所以你必须以某种方式使用那个新实例。
你没有在你的代码中这样做。
此外,这是不可能的ForEach
。乍一看,以下方法可行:
m_days.ToList().ForEach(d => { d = d.Trim(); });
But that isn't going to help you either, because d
is not passed by reference, so you are only changing the local parameter that has been passed into your delegate and not the instance stored in the list.
但这也无济于事,因为d
不是通过引用传递的,所以您只更改已传递给委托的本地参数,而不是存储在列表中的实例。
You most likely want this:
你很可能想要这个:
var result = days.Split(',').Select(x => x.Trim()).ToList();
An alternate way without LINQ would look like this:
没有 LINQ 的另一种方法如下所示:
var split = days.Split(',');
for(int i = 0; i < split.Length; ++i)
split[i] = split[i].Trim();