Using LINQ to remove a suffix from a string if it contains a suffix in a list?

How can I remove the suffix from a string and return it using C # / LINQ? Example:

string[] suffixes = { "Plural", "Singular", "Something", "SomethingElse" };

string myString = "DeleteItemMessagePlural";

string stringWithoutSuffix = myString.???; // what do I do here?

// stringWithoutSuffix == "DeleteItemMessage"
+3
source share
3 answers
var firstMatchingSuffix = suffixes.Where(myString.EndsWith).FirstOrDefault();
if (firstMatchingSuffix != null)
    myString = myString.Substring(0, myString.LastIndexOf(firstMatchingSuffix));
+3
source

You need to create a regular expression from the list:

var regex = new Regex("(" + String.Join("|", list.Select(Regex.Escape)) + ")$");

string stringWithoutSuffix = regex.Replace(myString, "");
+2
source
// Assuming there is exactly one matching suffix (this will check that)
var suffixToStrip = suffixes.Single(x => myString.EndsWith(x));

// Replace the matching one:
var stringWithoutSuffix =  Regex.Replace(myString, "(" +suffixToStrip + ")$", "");

OR, since you know the length of the corresponding suffix:

// Assuming there is exactly one matching suffix (this will check that)
int trim = suffixes.Single(x => myString.EndsWith(x)).Length;

// Remove the matching one:
var stringWithoutSuffix =  myString.Substring(0, myString.Length - trim);
0
source

All Articles