2

Is there a way of of overwriting the value of variable of type Regex?

I have working code which looks as follows:

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_"); // probability of default
    fileList = fileList.Where(x => myRegexPD.IsMatch(x.FileName));
    break;
  case "fx":  // exchange rate
    Regex myRegexFx = new Regex("^FX_"); // exchange rate
    fileList = fileList.Where(x => myRegexFx.IsMatch(x.FileName));
    break;
  default:
    System.Diagnostics.Debug.WriteLine("File type not valid.");
    break;
}

In reality, this switch statement is much longer, so I would like to shorten things by doing something like the following:

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));

However, this gives various type conversion errors. Any suggestion how to tackle that?

References

B--rian
  • 5,578
  • 10
  • 38
  • 89

1 Answers1

4

I suggest organizing the patterns into a dictionary and get rid of switch ... case:

 //TODO: I've hardcoded the patterns, but you may well want to generate them:
 // s_Patterns = MyFileTypes.ToDictionary(t => t.Name, $"^{t.Name.ToUpper()}_"); 
 private static Dictionary<string, string> s_Patterns = new Dictionary<string, string>() {
   {"pd", "^PD_"},
   {"fx", "^FX_"},
 };

then you can easily use them:

 if (s_Patterns.TryGetValue(fileType, out var pattern))
   fileList = fileList.Where(x => Regex.IsMatch(x.FileName, pattern));
 else
   System.Diagnostics.Debug.WriteLine("File type not valid.");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    Thanks for the idea of using a dictionary, this is really a significant improvement of code structure, since now I can regex-outsource the logic (into a database), where it makes much more sense. – B--rian Feb 14 '20 at 11:47