-4

我有一个

List<string> names = new List<string>{"asa","@!","~!@#$%^tryt","asas**)_+lk"};//just an example...will be populated at run time
List<string> unsupportedCharacters = new List<string> { "~", "!", "#", "$", "%", "^", "&", "*"};

现在我想从“名称”列表中的每个字符串中删除不支持的字符。我可以通过 foreach 循环并检查每个字符串来做到这一点,但我想知道是否有更好的方法来实现这一点?可能正在使用 Linq 吗?

问题编辑

如果我必须用单个空格字符替换 unsupportedCharacters 怎么样......所以“My@@Naame!@%%Is~~Foo”应该转换为“My Name Is Foo”?当然所有字符串仍在列出“名称”

编辑 2 使用 Regex.Replace() 解决了它

4

2 回答 2

1

better way. 没有把握。不一样的方式?也许。

var names = new List<string> { "asa", "@!", "~!@#$%^tryt", "asas**)_+lk" };
var unsupportedCharacters = new HashSet<char>("~!#$%^&*");

var newNames = names.Select(n => String.Join("", n.Where(c => !unsupportedCharacters.Contains(c))))
                    .ToList();
于 2013-08-12T23:24:19.763 回答
0

这将为您提供所需的结果:

List<string> names = new List<string> { "asa", "@!", "~!@#$%^tryt", "asas**)_+lk" };
List<string> unsupportedCharacters = new List<string> { "~", "!", "#", "$", "%", "^", "&", "*" };
var result = names.Select(str => string.Concat(str.Split(unsupportedCharacters.ToArray(), StringSplitOptions.RemoveEmptyEntries)));
于 2013-08-12T23:50:33.563 回答