这个ForEach循环出了什么问题?

时间:2010-07-08 22:43:46

标签: c# foreach

是的......那是其中的一天。

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 _

两个ForEach循环都不起作用。 tagList只是一个List。

谢谢!

5 个答案:

答案 0 :(得分:5)

Trim()Replace()不会修改它们被调用的字符串。他们创建了一个已应用该操作的新字符串。

您想使用Select,而不是ForEach

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:2)

原因是字符串是不可变的。因此每个Trim()或Replace()函数的结果将产生一个新字符串。您需要重新分配原始元素才能看到更新后的值。

答案 3 :(得分:2)

这正是微软没有在IEnumerable上实现ForEach的原因。这有什么问题?

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

答案 4 :(得分:1)

如果不工作,你的意思是他们实际上没有做任何事情,我认为你需要稍微调整你的代码:

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 _

修剪和替换不会更改字符串的值,它们会返回新的字符串值。