假设我有以下用于Entity Framework 5 Code First的类。我需要搜索所有行业或部门的一系列关键字,返回所有与任何关键字匹配的潜在客户。我还需要搜索相同关键字的潜在客户名称。我坚持的是如何搜索多个关键字。
主类
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; }
}
行业类
public class Industry
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Lead> Leads { get; set; }
}
分类
public class Division
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Lead> Leads { get; set; }
}
服务/存储库调用
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;
}
以上查询适用于单个关键字。但是如果我在字符串中有多个单词并且我想匹配任何单个关键字,它就不起作用。
答案 0 :(得分:1)
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;
}
答案 1 :(得分:0)
您需要将字符串拆分为List并遍历每个关键字。这样的事情......(在我的头顶)
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;
}