简体   繁体   中英

Search Query in Linq with EF

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.

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;
    }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM