Linq distinct record containing keywords

前端 未结 12 2091
醉话见心
醉话见心 2021-02-19 05:09

I need to return a distinct list of records based on a car keywords search like: \"Alfa 147\"

The problem is that, as I have 3 \"Alfa\" cars, it returns 1 + 3 records (i

12条回答
  •  温柔的废话
    2021-02-19 06:10

    I tried this using LINQ directly against in memory collections (as in, not through SQL) - seems to work for me (I think the main point being that you want to search for Ads that apply to ALL the keywords specified, not ANY, correct? Anyway, some sample code below (a little comment-ish and not necessarily the most efficient, but hopefully illustrates the point...)

    Working with the following "data sets":

    private List AdCars = new List();
    private List KeywordAdCategories = new List();
    private List Categories = new List();
    private List Keywords = new List();
    

    which are populated in a test method using the data you provided...

    Search method looks a little like this:

    var splitKeywords = keywords.Split(' ');
    
    var validKeywords = Keywords.Join(splitKeywords, kwd => kwd.Name.ToLower(), spl => spl.ToLower(), (kwd, spl) => kwd.Id).ToList();
    
    var groupedAdIds = KeywordAdCategories
                    .GroupBy(kac => kac.Ad_Id)
                    .Where(grp => validKeywords.Except(grp.Select(kac => kac.Keyword_Id)).Any() == false)
                    .Select(grp => grp.Key)
                    .ToList();
    
    var foundKacs = KeywordAdCategories
        .Where(kac => groupedAdIds.Contains(kac.Ad_Id))
        .GroupBy(kbc => kbc.Category_Id, kac => kac.Ad_Id);
    
    //Results count by category
    var catCounts = Categories
        .Join(foundKacs, cat => cat.Id, kacGrp => kacGrp.Key, (cat, kacGrp) => new { CategoryName = cat.Name, AdCount = kacGrp.Distinct().Count() })
        .ToList();
    
    //Actual results set
    var ads = AdCars.Join(groupedAdIds, ad => ad.Id, grpAdId => grpAdId, (ad, grpAdId) => ad);
    

    As I said, this is more to illustrate, please don't look too closely at the use of Joins & GroupBy etc (not sure its exactly, er, "optimal")

    So, using the above, if I search for "Alfa", I get 3 Ad results, and if I search for "Alfa 147" I get just 1 result.

    EDIT: I've changed the code to represent two possible outcomes (as I wasn't sure which was needed by your question)

    ads will give you the actual Ads returned by the search

    catCounts will give a list of anonymous types each representing the find results as a count of Ads by category

    Does this help?

提交回复
热议问题