简体   繁体   English

条件字符串聚合.net

[英]conditional string aggregate .net

I have the following code 我有以下代码

var definitionMap = definitions.Aggregate("", (current, next) => 
    current +  "[\\W\\s]" + 
    next.Tag.Replace("(", "\\(").Replace(")", "\\)") + "[\\W\\s]" + "|");

This works pretty well except I get a trailing | 这很有效,除了我得到一个尾随| on the end, I could just remove this manually but is there anyway to stop the aggregate method from putting it there in the first place 最后,我可以手动删除它,但无论如何都要阻止聚合方法将它放在那里

You could add it conditionally at the start of each term, ie 您可以在每个学期开始时有条件地添加它,即

(current, next) => (current == "" ? "" : "|") + ...

However, I would also suggest you look at StringBuilder and a foreach loop here instead of Aggregate . 但是,我还建议您在这里查看StringBuilderforeach循环而不是Aggregate Actually, since StringBuilder has a fluent API you can actually use it inside Aggregate - but I don't recommend it. 实际上,由于StringBuilder有一个流畅的API,你实际上可以在Aggregate使用它 - 但我不推荐它。 Just because you can use a LINQ extension method doesn't mean it is automatically either clearer or better . 仅仅因为你可以使用LINQ扩展方法并不意味着它自动更清晰更好 In this case, it is neither IMO. 在这种情况下,它既不是IMO。 In particular, at the moment you are generating a lot of unnecessary intermediate strings. 特别是,目前你正在生成许多不必要的中间字符串。

Why not just go with String.Join and a Select ? 为什么不Select String.JoinSelect

var definitionMap =
    String.Join("|",
        definitions.Select(
            next =>
                "[\\W\\s]"
                + next.Tag.Replace("(", "\\(").Replace(")", "\\)")
                + "[\\W\\s]"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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