开发者

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. tagList is just a List.

Thank you!


Trim() and Replace() don't modify the string they're called on. They create a new string that has had the action applied to it.

You want to use Select, not ForEach.

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


ForEach (and other "linq" methods) does not modify the list instance.

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. 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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜