unom
unom

Reputation: 11476

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!

Upvotes: 1

Views: 252

Answers (5)

pdr
pdr

Reputation: 6440

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();

Upvotes: 2

Toan Nguyen
Toan Nguyen

Reputation: 11581

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.

Upvotes: 2

Anon.
Anon.

Reputation: 60008

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();

Upvotes: 5

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

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

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

Upvotes: 2

Sean Amos
Sean Amos

Reputation: 2391

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.

Upvotes: 1

Related Questions