gpt4 book ai didi

c# - 如何将字符串与 linq 中的 "filter"列表进行比较?

转载 作者:太空狗 更新时间:2023-10-29 21:09:23 27 4
gpt4 key购买 nike

我正在尝试通过“过滤器”列表来过滤字符串集合……坏词列表。该字符串包含列表中的一个词,我不想要它。

到目前为止,这里的坏词是“frakk”:

string[] filter = { "bad", "words", "frakk" };

string[] foo =
{
"this is a lol string that is allowed",
"this is another lol frakk string that is not allowed!"
};

var items = from item in foo
where (item.IndexOf( (from f in filter select f).ToString() ) == 0)
select item;

但这行不通,为什么?

最佳答案

您可以使用Any + Contains:

var items = foo.Where(s => !filter.Any(w => s.Contains(w)));

如果你想不区分大小写地比较:

var items = foo.Where(s => !filter.Any(w => s.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0));

更新:如果您想排除过滤器列表中至少有一个 的句子,您可以使用String.Split()Enumerable.Intersect:

var items = foo.Where(sentence => !sentence.Split().Intersect(filter).Any());

Enumerable.Intersect非常高效,因为它在底层使用了一个Set。将长序列放在第一位效率更高。由于 Linq 的延迟执行会在第一个匹配的单词处停止。

(请注意,“空”Split 包括其他空白字符,如制表符或换行符)

关于c# - 如何将字符串与 linq 中的 "filter"列表进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17890793/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com