C# 如果字符串在列表中包含后缀,则使用LINQ从字符串中删除后缀?
如何使用C#/LINQ从字符串中去掉后缀并返回它?例如:C# 如果字符串在列表中包含后缀,则使用LINQ从字符串中删除后缀?,c#,.net,linq,string,linq-to-objects,C#,.net,Linq,String,Linq To Objects,如何使用C#/LINQ从字符串中去掉后缀并返回它?例如: string[] suffixes = { "Plural", "Singular", "Something", "SomethingElse" }; string myString = "DeleteItemMessagePlural"; string stringWithoutSuffix = myString.???; // what do I do here? // stringWithoutSuffix == "Delet
string[] suffixes = { "Plural", "Singular", "Something", "SomethingElse" };
string myString = "DeleteItemMessagePlural";
string stringWithoutSuffix = myString.???; // what do I do here?
// stringWithoutSuffix == "DeleteItemMessage"
您需要从列表中构建正则表达式:
var regex = new Regex("(" + String.Join("|", list.Select(Regex.Escape)) + ")$");
string stringWithoutSuffix = regex.Replace(myString, "");
或者,因为您知道匹配后缀的长度:
// 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);
后缀重叠吗?你想删除多个后缀吗?+1-我会这么做的。或者newMyString=myString.Remove(myString.Length-suffix.Length)。如果找不到,FirstOrDefault()将给出null,然后在下一行上给出null异常。理想情况下,如果您想要一个,请使用Single(),它将更快地抛出(在较长的示例中可能是一个问题),并且语义更清晰。您也可以将条件放在单个(…)中。您应该检查null,或者只需使用
.First()
。如果不存在后缀,您的代码会在前面的一行出现一个令人讨厌的NullReferenceException
,因为firstMatchingSuffix
为空。您需要Regex.Escape
SuffExtoStrip
这是“可以”而不是“需要”,不是吗?总有不止一种方法;)
// 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 + ")$", "");
// 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);