tags:

views:

95

answers:

5

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!

+1  A: 

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.

Sean Amos
Yes, but here you just replace a local loop-var. I don't think this solves anything. The Analysis is right though.
Henk Holterman
True. Analysis is correct, the code produces the same result as mine.
basilmir
+2  A: 

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

tagList = tagList.Select(tag => tag.Trim().Replace(" ", "_")).ToList();
Joel Coehoorn
I do not believe `ForEach` is a LINQ method...it is a List<T> method. And I DO believe that ForEach is an action that is applied to each item at the time it is invoked...
jrista
@jrista - it's not a linq method. That's why it's in quotes.
Joel Coehoorn
@Joel: Right...however, it DOES apply the action immediately, its not delayed.
jrista
+4  A: 

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();
Anon.
Perfect! It works as advertised!
basilmir
+2  A: 

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.

DrakeVN
This is good also... providing the reason why it does not work.
basilmir
+2  A: 

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();
pdr
thankyou, someone with some actual sense. although you dont need the expense of a List, you know how many elements you have.
Andrew Bullock
This is ok too. I like it. Thanks :D
basilmir