Linq distinct record containing keywords

前端 未结 12 2153
醉话见心
醉话见心 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条回答
  •  Happy的楠姐
    2021-02-19 05:55

    So, if I understand the need correctly, you want all of the subset of words to be matched in the text and not the OR matching you are getting right now? I see at least two options, the first of which may not translate the split to SQL:

    var query = from k in keywordQuery where !splitKeywords.Except(k.Name.split(' ')).Any()
    

    This makes the following assumptions:

    1. Your words in the Keywords are space delimited.
    2. You are looking for exact matches and not partial matches. (I.e. Test will not match TestTest).

    The other option being to dynamically generate a predicate using predicate builder (haven't done this in a while, my implementation might need tweaking - but this is the more likely (and better in my mind) solution):

    var predicate = PredicateBuilder.True();
    foreach (string s in splitKeywords) {
        predicate.AND(s.Contains(k.Name));
    }
    
    query.Where(predicate);
    

    If someone can comment if some of my syntax is off I would appreciate it. EDIT: Including link to a good reference on predicate builder: http://www.albahari.com/nutshell/predicatebuilder.aspx

    UPDATE

    Predicate builder across multiple tables, if anyone gets here looking for how to do that. Can PredicateBuilder generate predicates that span multiple tables?

提交回复
热议问题