我有一个字符串列表和stringOutput示例:
readonly List<string> carMake = new List<string>
{
"Toyota",
"Honda",
"Audi",
"Tesla"
};
string myFunction()
{
// do some processing...
string stringOutput = CallGetLatestRecord();
// the above returns "a:toyota:c"
//Call another function after changing the string to "a:Toyota:c"
//I am planning to use **stringOutput.Replace**
//but don't know how to get toyota or list items values dynamically
callFoo(stringOutput);
}
所以这就是我想要的。如果我的:
如何使用Linq进行转换?
另外,请注意,在运行时我不知道它是丰田还是任何字符串...所以我想要使用Linq的通用解决方案
答案 0 :(得分:0)
下面的内容可以帮助你开始......
using System.Text.RegularExpressions;
string stringOutput = "a:toyota:c";
readonly List<string> carMake = new List<string>
{
"Toyota",
"Honda",
"Audi",
"Tesla"
};
string pattern = @".+?:(.+?):.+?";
foreach (Match m in Regex.Matches(stringOutput, pattern))
{
if (carMake.Any(s=>s.Equals(m.Groups[1].Value, StringComparison.InvariantCultureIgnoreCase)))
{
stringOutput = stringOutput.Replace(m.Groups[1].Value, carMake.First(s=>s.Equals(m.Groups[1].Value, StringComparison.InvariantCultureIgnoreCase)));
}
}
Console.WriteLine(stringOutput);
答案 1 :(得分:0)
你可以做这样的事情;
string Process(string stringOutput)
{
foreach (string c in carMake)
{
int i = stringOutput.IndexOf(c.ToLower());
if (i > -1)
{
stringOutput=stringOutput.Replace(c.ToLower(), c);
}
}
return stringOutput;
}