stooicrealism
stooicrealism

Reputation: 558

LINQ to SQL selecting all records which have any word in the string split

string1: How
string2: How Are you ?

What i want to do is select all records from the database by checking string2 against string1 and selecting any record which have either "How" or "Are" or "you".

 pager1.ItemCount = appliedQuery.Where(q => q.string1.Contains(string2)).count();

PlEASE NOTE: String1 is just one word and I just want to get all records in the db with any occurance of any word in string2.

I understand that string2 needs to split, however after the split how do i use it in the linq query statement to fetch the records?

Thanks in advance

Upvotes: 0

Views: 1533

Answers (3)

Carls Jr.
Carls Jr.

Reputation: 3078

Check out how I constructed my linq query. I hope this helps. Just try to copy and paste the code in your console app to see the result.

class Program
{
    static void Main(string[] args)
    {
        // List of strings that you may consider it from your 
        /// database which is String1
        List<string> lstStrings = new List<string>();
        lstStrings.Add("twenty one");
        lstStrings.Add("twenty two");
        lstStrings.Add("twenty three");
        lstStrings.Add("twenty four");

        // The string to compare to which is your String2
        string strString = "one two four";

        // Splitting the strings to be compared
        string[] strArray = strString.Split(' '); 

        // The linq that helps you query the data exactly as what you wanted
        var result = (from string A in lstStrings
                               from string B in strArray
                               where A.Contains(B)
                               select A).Distinct();

        // Count result
        Console.WriteLine(result.Count());

        // Individual values
        foreach (string str in result)
        {
            Console.WriteLine(str);
        }

        Console.ReadLine();
    } 
}

Upvotes: 1

rikitikitik
rikitikitik

Reputation: 2450

Split string2 into an array of strings:

string[] words = string2.Split(' ');

Then check if string1 is in any of the items in the array:

pager1.ItemCount = appliedQuery.Where(q => words.Contains(q.string1)).Count();

Upvotes: 2

Umesh
Umesh

Reputation: 2732

One possible solution could be following:

foreach(string s in string2.Split(' '))
{
    pager1.ItemCount += appliedQuery.Where(q => q.string1.Contains(s)).count(); 
}

Upvotes: 1

Related Questions