I need to make a search based on a set of keywords, that return all the Ads related with those keywords. Then the result is a list of Categories with the Ads Count for each
I think I have a solution now. This is based on your previous question and a few assumptions:
With those three assumptions in mind I can say that
var keywordIds = from k in keywordSearchQuery
where splitKeywords.Contains(k.Name)
select k.Keyword.Id;
is the culprit and all queries below rely on it. This query will find all keywords that contain any words in your searchstring.
Example: Given searchstring "Mercedes-Benz GLK" will be split into "Mercedes", "Benz" and "GLK". Your query now finds "Mercedes" and "Benz" in both "Mercedes-Benz GLK" and "Mercedes-Benz Citan".
I think it's obvious that you don't want "Mercedes-Benz GLK" to match "Mercedes-Benz Citan".
The solution is to tell the query to match every splitKeywords with any Keywordsearch and return the appropriate Keyword:
var keywordIds = keywordSearchQuery
.GroupBy(k => k.Keyword.Id)
.Where(g => splitKeywords.All(w =>
g.Any(k => k.Name.Contains(w))))
.Select(g => g.Key);
As for addIds changing it to var addIDs = matchingKac.Select(ad => ad.Ad_Id).Distinct();
should do the trick. Or if matchingKac is only needed in addIds then you could change it to
var matchingKac = (from kac in keywordAdCategoryQuery
where keywordIds.Distinct().Contains(kac.Keyword_Id)
select kac.Ad_Id).Distinct();
and remove addIds.