Reputation: 3210
Lets say I have the following classes for Entity Framework 5 Code First. I need to do a search of all the Industries or Divisions for an array of keywords, returning all the Leads that match any of the keywords. I also need to search the Name of the Lead for the same keywords. What I'm stuck on is how to search for multiple keywords.
Main Class
public class Lead
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Industry> Industries { get; set; }
public virtual ICollection<Division> Divisions { get; set; }
}
Industry Class
public class Industry
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Lead> Leads { get; set; }
}
Division Class
public class Division
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Lead> Leads { get; set; }
}
Service / Repository Call
public IQueryable<Lead> GetByKeywords(string keyword)
{
var result = leadRepository.GetAll().Where
(x => x.Industries.Any(i => i.Name == keyword)
|| x.Divisions.Any(d => d.Name == keyword)
|| x.Name.Contains(keyword));
return result;
}
The above query works for a single keyword. But it does not work if I have multiple words in the string and I want to match to any of the individual keywords.
Upvotes: 2
Views: 314
Reputation: 12315
public IEnumerable<Lead> GetByKeywords(string[] keywords)
{
var result = GetAll().Where
(x =>x.Industries.Any(i => keywords.Any(kw=>kw==i.Name))
|| x.Divisions.Any(d =>keywords.Any(k=>x.Name==k))
|| keywords.Any(kew => x.Name.Contains(kew)));
return result;
}
Upvotes: 1
Reputation: 11308
You'll need to split your string into a List and loop through each keyword. Something like this... (off the top of my head)
IQueryable<Lead> GetByKeywords(string allKeywords)
{
List<string> keywords = allKeywords.Split(" ");
var result = leadRepository.GetAll();
foreach (string keyword in keywords)
{
result = result.Where
(x => x.Industries.Any(i => i.Name == keyword)
|| x.Divisions.Any(d => d.Name == keyword)
|| x.Name.Contains(keyword));
}
return result;
}
Upvotes: 0