是否有一种方法可以覆盖类型为Regex
的变量的值?
我有如下工作代码:
string[] dirEntries = Directory.GetFiles(inputDir, "*.csv", SearchOption.TopDirectoryOnly);
var fileList = dirEntries
.Select(x => new FileMetaDto
{
FileName = Path.GetFileName(x),
FullPath = x,
FileType = fileType,
});
switch (fileType)
{
case "pd": // probability of default
Regex myRegexPD = new Regex("^PD_");
fileList = fileList.Where(x => myRegexPD.IsMatch(x.FileName));
break;
case "fx": // exchange rate
Regex myRegexFx = new Regex("^FX_");
fileList = fileList.Where(x => myRegexFx.IsMatch(x.FileName));
break;
default:
System.Diagnostics.Debug.WriteLine("File type not valid.");
break;
}
实际上,此switch
语句要长得多,所以我想通过执行以下操作来缩短时间:
my Regex myRegex = new Regex();
switch (fileType)
{
case "pd":
myRegex = "^PD_";
break;
case "fx":
myRegexFx = "^FX_";
break;
default:
System.Diagnostics.Debug.WriteLine("File type not valid.");
myRegEx = "*";
break;
}
fileList = fileList.Where(x => myRegex.IsMatch(x.FileName));
但是,这会产生各种类型转换错误。任何建议如何解决这个问题?
将模式存储为字符串:
string pattern;
switch (fileType)
{
case "pd":
pattern = "^PD_";
break;
case "fx":
pattern = "^FX_";
break;
default:
System.Diagnostics.Debug.WriteLine("File type not valid.");
pattern = "*";
break;
}
fileList = fileList.Where(x => Regex.IsMatch(x.FileName, pattern));