为什么我尝试修剪 List中的字符串会失败? 似乎不起作用?
我在 LINQPad 中尝试了以下代码并得到了以下结果:
List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump();
listFromSplit.ForEach(delegate(string s)
{
s.Trim();
});
listFromSplit.Dump();
“a”和“b”
,所以字母 b 没有像我预期的那样删除空格......?
任何人都有任何想法
[注意:.Dump() 方法是 LINQPad 中的扩展方法,它以良好的智能格式方式打印出任何对象的内容]
I tried the following code in LINQPad and got the results given below:
List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump();
listFromSplit.ForEach(delegate(string s)
{
s.Trim();
});
listFromSplit.Dump();
"a" and " b"
so the letter b didn't get the white-space removed as I was expecting...?
Anyone have any ideas
[NOTE: the .Dump() method is an extension menthod in LINQPad that prints out the contents of any object in a nice intelligently formatted way]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您只是创建一个修剪过的字符串,而不是为其分配任何内容。
不会更新,而..
将..
我想,这就是我的处理方式。
you're just creating a trimmed string, not assigning anything to it.
won't update s, while..
will..
would, i suppose, be how i'd go about it.
String.Trim() 方法返回表示更新后的字符串的字符串。 它不会更新字符串对象本身,而是创建一个新的字符串对象。
您可以这样做:
但是,您无法在枚举集合时更新集合,因此您需要在枚举现有列表时填充新列表,或者使用 String.Split 返回的字符串数组手动填充列表。
填充新列表:
手动填充:
The String.Trim() method returns a string representing the updated string. It does not update the string object itself, but rather creates a new one.
You could do this:
However you cannot update a collection while enumerating through it so you'd want to either fill a new List while enumerating over the existing one or populate the List manually using the string array returned by String.Split.
Filling a new list:
Populating Manually:
进一步回答 Adrian Kuhn 您可以执行以下操作:
Further to the answer posted by Adrian Kuhn you could do the following:
字符串实例是不可变的。 任何看似修改实例的东西都会创建一个新实例。
The string instances are immutable. Anything that seems to modify one, creates a new instance instead.
您没有将修剪结果分配给任何东西。 这是一个典型的错误,我刚刚摆脱了使用 string.Replace 犯这个错误的习惯:)
You are not assigning the trimmed result to anything. This is a classic error, I've only just got out of the habit of making this mistake with string.Replace :)
我没有启动并运行 IDE,但这应该可以完成工作(除非我错了):
I have no IDE up and running, but this should get the job done (unless I am wrong):
按空格和逗号拆分并删除所有空条目。 一切都很好,修剪整齐。 不过,假设您的字符串不包含空格。
Split on both spaces and commas and remove any empty entries. All nice and trimmed. Assumes that your strings don't contain spaces, though.
其他人提供的 linq 选项应该可以很好地工作。 作为另一种选择,这里是使用 for 循环的扩展方法:
The linq options others have provided should work well. As another option, here is an extension method using a for loop: