简体   繁体   中英

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(和其他“ 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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