0

I have a simple function that loops through a static string array and tests to see if a string contains any instance of the array. If true, then the text from the string is removed (replaced with an empty string).

This function works, but I need to create a LINQ expression to do this (or a one-line expression). I can't figure out how to do this unless I turn my string s into an array. But if I do that then it complicates trying to match the facilities strings. How can I accomplish this in a one-liner?

  private static string[] facilities = { "MX10", "MX80", "MX81", "MX82", "MX83", "US00", "US10", "US11", "US20", "US30", "US50", "US60", "US70", "US99" };
  
  private static string cleansePN(string s)
  {
      for (int i = 0; i < facilities.Length; i++)
      {
          s = s.Replace(facilities[i], string.Empty);
      }
      return s;
  }
4
  • 1
    If the facilities array really is static, have you considered just making a RegEx from it? RegEx replace would be the simpler and faster than LINQ over an array. Commented Dec 16, 2020 at 16:22
  • @IanMercer I like this... so its essentially return Regex.Replace(s, @"MX10|MX80|...", string.Empty); Commented Dec 16, 2020 at 16:29
  • 1
    Maybe Regex r = new Regex("MX[0-9]+|US[0-9]+", RegexOptions.Compiled); if you want to catch all MX and US followed by one or more digits. Or you could make it more precise if it's always two digits. Commented Dec 16, 2020 at 18:42
  • 1
    Does this answer your question? string replace using Linq in c# Commented Dec 17, 2020 at 15:20

1 Answer 1

4

Linq Aggregate:

private static string cleansePN(string s)
{
    return facilities.Aggregate(s, (current, t) => current.Replace(t, string.Empty));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Would you say that the for loop is faster (given a string of 10-30 characters) or is it negligible?
@bagofmilk Aggregate uses inside foreach, so, it's equal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.