string 在 C# 中使用 Linq 替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5137514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:00:13  来源:igfitidea点击:

string replace using Linq in c#

linqstringreplaceusing

提问by GaneshT


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

I have a list of Abbreviation objects like this:

我有一个像这样的缩写对象列表:


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")
...

I expect the result to be: "this is a test expression in a paragraph contains answer for a question"

我希望结果是:“这是一个段落中的测试表达式,包含一个问题的答案”

Currently I am doing:

目前我正在做:


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

Wondering if there is a better way using a combination of Linq and Regex.

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

回答by p.campbell

If you really wanted to shorten your code, you could use the ForEachextension method on the List:

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

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

回答by Mike Cole

You could use the ForEach method. Also, a StringBuilder should make the operations on your string more efficient:

您可以使用 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();

回答by rejo

Try this one

试试这个

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

or the one below

或者下面那个

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