2

假设我有以下用于 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;
    }

上述查询适用于单个关键字。但是,如果字符串中有多个单词并且我想匹配任何单个关键字,则它不起作用。

4

2 回答 2

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;
    }
于 2013-07-11T05:15:02.083 回答
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;
}
于 2013-07-11T00:26:18.323 回答