1

I'm passing a string to a controller, and need the controller to search for ANY of the words passed, within the Title field of my database.

eg. id="outlook error message"

 [HttpPost]
    public JsonResult Lookup(string id)
    {
        List<string> listOfSearch = id.Split(' ').ToList();
        var results = db.KS.Where(x => x.Title.Intersect(listOfSearch).Any());

This produces the following two errors:

Instance argument: cannot convert from 'string' to 'System.Linq.IQueryable<string>

'string' does not contain a definition for 'Intersect' and the best extension method overload 'System.Linq.Queryable.Intersect<TSource>(System.Linq.IQueryable<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments

Can anyone please advise what's wrong, or how to populate results with just a list of Titles that contain any of the words passed in?

Thanks, Mark

Community
  • 1
  • 1
Mark
  • 7,778
  • 24
  • 89
  • 147
  • I had a similar question not long ago: http://stackoverflow.com/questions/16215100/linq-to-entities-orderby-statement-involving-extension-method (it has an answer to the problem you're having) – HennyH Apr 30 '13 at 10:58

3 Answers3

2
var results = db.KS.Where(x => listOfSearch.Any(item => x.Title.Contains(item)));

Update:
For LinqToSql:

var titles = db.KS.Select(item => item.Title)
    .AsEnumerable()
    .Where(title => listOfSearch.Any(word => title.Contains(word)));
Vladimir
  • 7,345
  • 4
  • 34
  • 39
  • Hi - this looks like it would work - but if I pass in "outlook err..." it will only return items where it has "outlook err.." specifically, not "outlook" or "error" - do you know how to achieve that please? Thank you, Mark – Mark Apr 30 '13 at 13:53
  • Sorry my mistake - it does work - it's the Twitter TypeAhead which is only hilighting entries where all text appears. That's another question though :) Thank you, Mark – Mark Apr 30 '13 at 14:09
2

you can try

 List<string> listOfSearch = id.Split(' ').ToList();
 var result = from item in db.KS
              where listOfSearch.Any(v => item.Title.Contains(v)) 
              select item;

or

var result = db.KS.Where(item => listOfSearch.Any(v => item.Title.Contains(v)));
Cloudsan Chen
  • 329
  • 1
  • 10
1

Change the statement to:

db.KS.Intersect(.... 

KS returns you the IQueryable on which you can directly perform the intersection.

Biswanath
  • 9,075
  • 12
  • 44
  • 58