【问题标题】:string replace using Linq in c#在 C# 中使用 Linq 替换字符串
【发布时间】:2011-07-05 11:35:29
【问题描述】:

public class Abbreviation
{
    public string ShortName { get; set; }
    public string LongName { get; set; }
}

我有一个 Abbreviation 对象列表,如下所示:


List abbreviations = new List();
abbreviations.add(new Abbreviation() {ShortName = "exp.", LongName = "expression"});
abbreviations.add(new Abbreviation() {ShortName = "para.", LongName = "paragraph"});
abbreviations.add(new Abbreviation() {ShortName = "ans.", LongName = "answer"});

string test = "this is a test exp. in a para. contains ans. for a question";

string result = test.Replace("exp.", "expression")
...

我希望结果是: "this is a test expression in a paragraph contains answer for a question"

目前我在做:


foreach (Abbreviation abbreviation in abbreviations)
{
    test = test.Replace(abbreviation.ShortName, abbreviation.LongName);
}
result = test;

想知道是否有更好的方法结合使用 Linq 和 Regex。

【问题讨论】:

  • LINQ 不能解决所有问题,你写的很好。

标签: linq string replace using


【解决方案1】:

试试这个

TestList.ForEach(x => x.TestType.Replace("", "DataNotAvailable"));

或者下面那个

foreach (TestModel item in TestList.Where(x => x.ID == ""))
{
    item.ID = "NoDataAvailable";
}

【讨论】:

    【解决方案2】:

    如果你真的想缩短你的代码,你可以在List上使用ForEach扩展方法:

    abbreviations.ForEach(x=> test=test.Replace(x.ShortName, x.LongName));
    

    【讨论】:

    • 技术上这不是 LINQ ;-)
    • 从技术上讲,它也不是函数式编程 - blogs.msdn.com/b/ericlippert/archive/2009/05/18/…
    • 我知道总有比我通常做的更好的方法。它工作得很好。谢谢你和迈克。
    • 我想要相同的,但我如何找到字符串的一部分并将其替换为其他文本?请提出建议。
    【解决方案3】:

    您可以使用 ForEach 方法。此外,StringBuilder 应该使对字符串的操作更高效:

    var test = new StringBuilder("this is a test exp. in a para. contains ans. for a question");
    abbreviations.ForEach(abb => test = test.Replace(abb.ShortName, abb.LongName));
    return test.ToString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 2015-05-21
      • 1970-01-01
      • 2019-11-01
      • 2011-10-20
      相关资源
      最近更新 更多