问题
Thanks NetMage for answering my question in Linq search text using 'and' operator
Now, please let me ask some more complicated:
I have the following tables where localizationdata.EntryId
is linked to mascotcategories.Id
and mascots.Id
depending on the localizationdata.Type
value.
`localizationdata` (
`Id` int(11)`, Type` varchar(45),
`EntryId` int(11),
`LanguageId` int(11),
`Value` varchar(150) }
`mascots` (
`Id` int(11), `Name` varchar(100),
`MascotCategoryId` int(11),
`UserId` varchar(100),
`mascotcategories` (
`Id` int(11), `CategoryName` varchar(45),
`IsVisible` bit(1),
`ParentId` int(11) DEFAULT NULL,
`SawgrassOnly` bit(1)
I need again to 'AND' search (as in my previous question in the link above) the localizationdata.value
which contains the translated word for mascotcategories.CategoryName
and mascots.Name
.
For example, the user would enter French keywords "bleu ici" in which the 'bleu ' comes from localizationdata.Value
that has the translated category name and 'ici' comes from localizationdata.Value
too that has the mascot's translated name. I need the mascots that contain both the above words to their name and to their categories' name. Is this feasible?
回答1:
I am not sure how optimal this is, but I believe it works:
First, reduce the two types of localization down to one common type:
var mascotNameLocalized = from ld in db.localizationdata
where ld.Type == "mascot"
group ld by ld.EntryId into ldg
select new { MascotId = ldg.Key, Words = ldg.Select(g => g.Value) };
var mascotCategoriesLocalized = from ld in db.localizationdata
where ld.Type == "mascotcategory"
join mc in db.mascotcategories on ld.EntryId equals mc.Id
join m in db.mascots on mc.Id equals m.MascotCategoryId into mj
where mj.Any()
from m in mj
group ld by m.Id into ldg
select new { MascotId = ldg.Key, Words = ldg.Select(g => g.Value) };
Then combine them into one common list:
var mascotsLocalized = from m in mascotNameLocalized.Concat(mascotCategoriesLocalized)
group m by m.MascotId into mg
select new { MascotId = mg.Key, Words = mg.SelectMany(m2 => m2.Words).ToList() };
Then find all mascots that match all the search terms:
var srch = "bleu ici";
var srchwords = srch.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var ans = from m in mascotsLocalized
where srchwords.All(sw => m.Words.Contains(sw))
select m.MascotId;
来源:https://stackoverflow.com/questions/45516773/linq-search-text-using-and-operator-in-joined-fields-from-different-tables