如果列表中包含后缀,则使用LINQ从字符串中去除后缀?

时间:2011-06-12 02:37:35

标签: 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 == "DeleteItemMessage"

3 个答案:

答案 0 :(得分:3)

var firstMatchingSuffix = suffixes.Where(myString.EndsWith).FirstOrDefault();
if (firstMatchingSuffix != null)
    myString = myString.Substring(0, myString.LastIndexOf(firstMatchingSuffix));

答案 1 :(得分:2)

您需要从列表中构建正则表达式:

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

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

答案 2 :(得分:0)

// 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,因为您知道匹配后缀的长度:

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