在字符串列表中查找字符串列表简化为 SQL

Find List of string in List of strings simplify like in SQL

我想知道如何才能在字符串列表中找到我的字符串列表。

我找到了其他解决方案,但大多数解决方案只能在字符串列表中找到一个单词,但我的不一样。

为了简单易懂,我制作了一个 SQL 脚本,在 C# 中实现了我需要的 objective。谢谢。

*;WITH cteFindTheseWords (Word) AS (
    SELECT 'One' UNION ALL
    SELECT 'Two' UNION ALL
    SELECT 'Three' UNION ALL
    SELECT 'Four' 
), cteFindWordsHere (FindHere) AS (
    SELECT 'One Two' UNION ALL
    SELECT 'Earth' UNION ALL
    SELECT 'Land Four' UNION ALL
    SELECT 'The One' UNION ALL
    SELECT 'Hello Wolrd' UNION ALL
    SELECT 'World Everest' UNION ALL
    SELECT 'Then now Two' 
)
SELECT *
FROM cteFindWordsHere a
    JOIN cteFindTheseWords b ON a.FindHere LIKE '%'+ b.Word +'%'*

这里需要解决3个问题:

  1. 测试字符串是否包含给定的子字符串
  2. 针对多个子字符串any测试上述条件
  3. 将此应用到 字符串列表

要测试给定的子字符串(即 "One")是否出现在给定的字符串(即“One Two”)中,您可以使用 the string.IndexOf() method:

var indexOfSubstring = "One Two".IndexOf("One");
if(indexOfSubstring >= 0){
    // substring was found in string
}

要测试子字符串列表中的是否符合上述条件,我们可以使用the LINQ Any() method:

var substrings = new string[] { "One", "Two", "Three", "Four" };
substrings.Any(s => "One Two".IndexOf(s) >= 0)

最后,要过滤整个字符串列表,我们可以使用 the LINQ Where() method:

var strings = new string[] { "One Two", "Earth", "Land Four", "The One", "Hello Wolrd", "World Everest", "Then now Two" };
var substrings = new string[] { "One", "Two", "Three", "Four" };

var filteredList = strings.Where(w => substrings.Any(s => w.IndexOf(s) >= 0)).ToList();

如果需要 i 不区分大小写的比较,将 StringComparison 实例传递给 IndexOf() 调用:

var filteredList = strings.Where(w => substrings.Any(s => w.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0)).ToList();