sJacobs
sJacobs

Reputation: 13

Sql to Linq like syntax

How would I write a linq query in C# for the table SomeTable where MyCol contains all words from a list? Is there some way to easily write a Like statement for this?

I've searched the internet for an answer to my problem, but wasn't able to find things that quite fit. In Linq, there is the contains, startsWith, and endsWith methods. These really help if I have an SQL statement like:

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

But. What I have is a statement like this:

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

This would in effect cause @Wild_Name to equal %my%cat%likes%dogs and now I'm searching for every one of those words in order with possibly something in between in this statement:

select * from SomeTable where MyCol like @WildName 

A result that can be pulled up by this query is That's my cat. He really likes black dogs Am I going about this the wrong way?

Upvotes: 1

Views: 128

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61379

This is definitely possible, though there is no "Like" in LINQ.

Something like this will do the trick:

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));

Pre-splitting test_string would likely provide a performance boost (since you only split once). Also this assumes that all words are space delimited.

To ensure that they come in the correct order:

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;

I couldn't come up with a "pure" LINQ way of doing this, but maybe it will help you come up with some ideas!

Let me know if I can clarify anything!

Upvotes: 1

Related Questions