0

Been struggling with this and don't know how to implement. Seems easy of enough.

I have a search box that takes multiple keywords. I then take those keywords and pass them to my IENumerable method in my repository.

public IEnumerable<diss> GetDissSearch(string b)

Then I place keywords into array - b contains the string of words and use Split method.

string[] sArray = strSearchString.Split();

Then I use foreach loop to go words in my array, but within my foreach loop I place my linq statement as the following:

foreach(string s in sArray){

var myLoop = (from p in mytable
              where p.userFirstName.Contains(s)
              && p.lastName.Contains(s)
              select new myModel {
              firstName = p.userFirstName,
              lastName = p.userLastName
              }).ToList();

return myLoop;

}

So if user enters two words - for example, a first and last name, you expect that the collection would be called twice. Similarly if user entered a middle name then collection would be called three times. At the moment, this collection is only run once.

Is there way to call this ienumerable multiple times based on the number of keywords contained in my array?

Thanks.

1 Answer 1

2

Wrap the searching query with the Any (or All if you want all the sArray terms to exist) ex. method, in this way each DB row will be evaluated against the array just once:

var myLoop = (from p in mytable
              where sArray.Any(sa => p.userFirstName.Contains(sa)
              && p.lastName.Contains(sa))
              select new myModel
              {
                firstName = p.userFirstName,
                lastName = p.userLastName
              }).ToList();

Also, consider replacing the && operator in your query with || if you want the terms to be in either first name or last name.

Sign up to request clarification or add additional context in comments.

1 Comment

This is great! Thanks so much, and yes, the && was a typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.