Sql to Linq 類似的語法

本文关键字:to Linq Sql | 更新日期: 2023-09-27 17:56:33

如何在 C# 中为包含列表中所有单词MyCol的表SomeTable编写 linq 查询?有没有办法轻松地为此编写 Like 语句?

我已经在互联网上搜索了我问题的答案,但找不到合适的东西。在 Linq 中,有containsstartsWithendsWith 方法。如果我有一个 SQL 语句,这些真的很有帮助,例如:

select * from SomeTable where Col_1 like '%cat' or Col_2 like 'dog%' or Col_3 like     '%Random%'

但。我有这样的声明:

declare @Wild_Name varchar(500) = 'my cat likes dogs'
set @Wild_Name='%'+REPLACE(@Wild_Name,' ','%')

这实际上会导致@Wild_Name等于%my%cat%likes%dogs,现在我正在搜索这些单词中的每一个,并可能在此语句中介于两者之间:

select * from SomeTable where MyCol like @WildName 

此查询可以提取的结果是That's my cat. He really likes black dogs我这样做的方式是错误的吗?

Sql to Linq 類似的語法

这绝对是可能的,尽管 LINQ 中没有"Like"。

像这样的东西就可以了:

string wild_name = "my cat likes dogs";
string test_string = "That's my cat. He really likes black dogs";
bool match = wild_name.Split(' ').All( w => test_string.Split(' ').Contains(w));

预拆分test_string可能会提高性能(因为您只拆分一次)。此外,这假设所有单词都是空格分隔的。

要确保它们以正确的顺序排列,请执行以下操作:

string wild_name = "my cat likes dogs";
string test_string = "That's my cat. He really likes black dogs";
string[] wildStrings = wild_name.Split(' ');
int lastFoundIndex = 0;
bool success = true;
for (int i = 0; i < wildStrings.Length; i++)
{
   if (test_string.Split(' ').Contains(wildStrings[i])
   {
      int findIndex = test_string.Split(' ').IndexOf(wildStrings[i]);
      if (findIndex < lastFoundIndex)
      {
         success = false;
         break;
      }
   }
   else
   {
       success = false;
       break;
   }
}
return success;

我无法想出一种"纯粹"的 LINQ 方法来做到这一点,但也许它会帮助你提出一些想法!

如果我能澄清任何事情,请告诉我!