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

Var firstMatchingSuffix = suffixes. Where(myString. EndsWith).FirstOrDefault(); if (firstMatchingSuffix!

= null) myString = myString. Substring(0, myString. LastIndexOf(firstMatchingSuffix)).

1 - what I would have done. Alternately newMyString = myString. Remove(myString.

Length - suffix. Length). – TrueWill Jun 12 at 2:49 1 FirstOrDefault() will give a null if not found and then a null exception on the following line.

Ideally if you want precisely one, use Single() and it will throw sooner (can be an issue in longer examples) and the semantics are cleaner. You can also put the condition inside the Single(...). – ghtechrider Jun 12 at 2:53 you should check for null or you can just use .First().

If no suffix is present your code crashes a line ahead with a nasty NullReferenceException because firstMatchingSuffix is null. – Zebi Jun 12 at 2:54 @ @Zebi - right, fixed. – Alex Aza Jun 12 at 2:56.

You need to build a regular expression from the list: var regex = new Regex("(" + String. Join("|", list. Select(Regex.

Escape)) + ")$"); string stringWithoutSuffix = regex. Replace(myString, "").

There is always more than one way ;) – ChrisWue Jun 12 at 2:57.

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 matching 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).

You need to Regex. Escape suffixToStrip – Alex Aza Jun 12 at 2:52.

Var suffixToStrip = suffixes. Single(x => myString. Var stringWithoutSuffix = Regex.

Int trim = suffixes. Single(x => myString. Var stringWithoutSuffix = myString.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions