【问题标题】:What's wrong with this ForEach loop?这个 ForEach 循环有什么问题?
【发布时间】:2010-07-08 22:43:46
【问题描述】:

是的......这是那些日子之一。

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 只是一个列表。

谢谢!

【问题讨论】:

  • 请不要说他们“不工作”。请描述您预期会发生什么,以及您实际观察到什么。

标签: c# foreach


【解决方案1】:

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

您想使用Select,而不是ForEach

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我不相信ForEach 是一种 LINQ 方法...它是一种 List 方法。而且我相信 ForEach 是一个在每个项目被调用时应用的操作......
    • @jrista - 这不是 linq 方法。这就是为什么它在引号中。
    • 对...但是,它会立即应用该操作,而不是延迟。
    【解决方案3】:

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

    【讨论】:

    • 这也很好......提供它不起作用的原因。
    【解决方案4】:

    这正是微软没有在 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();
    

    【讨论】:

    • 谢谢你,一个有实际意义的人。虽然你不需要 List 的开销,但你知道你有多少元素。
    • 这也可以。我喜欢。谢谢:D
    【解决方案5】:

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

    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 和 Replace 不会改变字符串的值,它们会返回新的字符串值。

    【讨论】:

    • 是的,但是在这里您只需替换一个本地循环变量。我不认为这可以解决任何问题。不过分析是对的。
    • 是的。分析是正确的,代码产生的结果和我的一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多