简体   繁体   English

此ForEach循环有什么问题?

[英]What's wrong with this ForEach loop?

Yep... it's one of those days. 是的...那是其中的一天。

public string TagsInput { get; set; }

//further down
var tagList = TagsInput.Split(Resources.GlobalResources.TagSeparator.ToCharArray()).ToList();
tagList.ForEach(tag => tag.Trim()); //trim each list item for spaces
tagList.ForEach(tag => tag.Replace(" ", "_")); //replace remaining inner word spacings with _

Both ForEach loops don't work. 两个ForEach循环均无效。 tagList is just a List. tagList只是一个列表。

Thank you! 谢谢!

Trim() and Replace() don't modify the string they're called on. Trim()Replace()不会修改调用它们的字符串。 They create a new string that has had the action applied to it. 他们创建一个新字符串,该字符串已应用了操作。

You want to use Select , not ForEach . 您要使用Select而不是ForEach

tagList = tagList.Select(t => t.Trim()).Select(t => t.Replace(" ", "_")).ToList();

ForEach(和其他“ linq”方法)不会修改列表实例。

tagList = tagList.Select(tag => tag.Trim().Replace(" ", "_")).ToList();

The reason is string is immutuable. 原因是字符串是不可改变的。 So the result of each Trim() or Replac() function will produce a new string. 因此,每个Trim()或Replac()函数的结果都会产生一个新的字符串。 You need to reassign to the original element in order to see the updated value. 您需要重新分配给原始元素才能查看更新后的值。

This is exactly why Microsoft havent implemented ForEach on an IEnumerable. 这正是Microsoft尚未在IEnumerable上实现ForEach的原因。 What's wrong with this? 这怎么了

public string[] TagsInput { get; set; }

//further down
var adjustedTags = new List<string>();
foreach (var tag in TagsInput.Split(Resources.GlobalResources.TagSeparator.ToCharArray()))
{
    adjustedTags.Add(tag.Trim().Replace(" ", "_"));
}

TagsInput = adjustedTags.ToArray();

If by don't work, you mean that they don't actually do anything, I think you need to adjust your code a bit: 如果不起作用,则表示他们实际上没有执行任何操作,我认为您需要稍微调整一下代码:

public string TagsInput { get; set; }

//further down
var tagList = TagsInput.Split(Resources.GlobalResources.TagSeparator.ToCharArray()).ToList();
tagList.ForEach(tag => tag = tag.Trim()); //trim each list item for spaces
tagList.ForEach(tag => tag = tag.Replace(" ", "_")); //replace remaining inner word spacings with _

Trim and Replace don't change the value of the string, they return the new string value. 修剪和替换不会更改字符串的值,它们会返回新的字符串值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM