使用LINQ lambda替换string中的数组中的字符

时间:2016-05-24 08:36:38

标签: c# arrays linq replace

我的字符串数组包含不允许的字符:

public static string[] IllegalCharacters = { "\"", "/", "\\", "[", "]", ":", "|", "<", ">", "+", "=", ";", ",", "?", "*", "\'", "@", ".", ":", "^", "¨", "å", "ä", "ö", "Å", "Ä", "Ö" };

我可以用这样的foreach一个接一个地删除这些字符:

private string RemoveIllegalCharactersFromString(string text)
{
    foreach (string illegalCharacter in IllegalCharacters.IllegalCharacters)
    {
        text = text.Replace(illegalCharacter, "");
    }
    return text;
}

我的问题是我可以使用linq lambda表达式删除方法吗?

我现在正在使用的是:

public static HashSet<char> IllegalCharacters = new HashSet<char>(new char[] { '\"', '/', '\\', '[', ']', ':', '|', '<', '>', '+', '=', ';', ',', '?', '*', '\'', '@', '.', ':', '^', '¨','\'' });

var t = sourceText.Where(c => !IllegalCharacters.Contains(c)).ToArray();
var result = new string(t);
return result;

3 个答案:

答案 0 :(得分:4)

我建议将IllegalCharacters更改为char集合(非法字符应为字符,对吧?),例如。

  public static HashSet<char> IllegalCharacters = new HashSet<char>(
    new char[] { '"', '\\', ..., 'Ä', 'Ö' });

所以你可以把一个明显的Linq:

  string source = "123:+-456";

  string result = String.Concat(source
   .Where(c => !IllegalCharacters.Contains(c)));

答案 1 :(得分:3)

以下是Linq的方法

string Text = "1:2+3[4]5|6";
string Result = new string(Text.Where(x => !IllegalCharacters.Contains(x.ToString())).ToArray());

我会将字符存储在char类型而不是string中,并使用HashSet代替string[]

HashSet<char> IllegalCharacters = new HashSet<char>() { '\'', '/', '\\', '[', ']', ':', '|', '<', '>', '+', '=', ';', ',', '?', '*', '\'', '@', '.', ':', '^', '¨', 'å', 'ä', 'ö', 'Å', 'Ä', 'Ö' };

string Text = "1:2+3[4]5|6";
string Result = new string(Text.Where(x => !IllegalCharacters.Contains(x)).ToArray());

答案 2 :(得分:2)

您可以使用Aggregate。像这样:

private string RemoveIllegalCharactersFromString(string text)
{
    return IllegalCharacters.Aggregate(text, (current, illegalCharacter) => current.Replace(illegalCharacter, ""));
}

结果:

string result = RemoveIllegalCharactersFromString("HelloÄ[2536]:Y?eÖs*");
//Result => Hello2536Yes