Dynamic linq-to-sql that queries based on multiple keywords

I put together a simple little search.

IEnumerable<Member> searchResults = (from m in members
                                     where m.ScreenName.ToUpper().Contains(upperKeyword)
                                     select m).AsEnumerable();

Then I realized this, if the user typed "keyword1 keyword2", this little query will always look for this exact string. So, I decided that I should probably separate the keywords

string[] keywords = upperKeyword.split(' ');

and then I ran into a problem. I can not do it:

IEnumerable<Member> searchResults = (from m in members
                                     where m.ScreenName.ToUpper().Contains(keywords) // array of string
                                     select m).AsEnumerable();

because it .Contains()does not accept an array. How could I do this?

+3
source share
3 answers

Try this one (untested):

IEnumerable<Member> searchResults = members.ToList().Where(m => keywords.Any(k => m.Summary.Contains(k)))

Edit

Added .ToList (), since I do not think LINQ will be able to convert the above to SQL, so we will need to execute this in memory.

+2
source

For exact matches:

, : where keywords.Contains(m.ScreenName)

IN LINQ-to-SQL

:

string[] keywords = new[]{ ... };
var results = db.members.Where(m => keywords.Any(sn => m.ScreenName.Contains(sn)));

, .

+1

, . , , .

IEnumerable<Member> searchResults = (from m in members
                                     where keywords.ToList().Contains(m.ScreenName.ToUpper()) // array of string
                                     select m).AsEnumerable();
0
source

Source: https://habr.com/ru/post/1783300/


All Articles