我正在尝试从linq查询中获取匹配项-
public ActionResult TagFilter(TagModel tag) {
List<CardModel> cardlist = null;
var cardtaglist = (from u in db.CardTagTables
where u.CardTagName == tag.tagName
select u).ToList();
cardlist = (from u in db.CardTables
where u.CardID == cardtaglist.Where(e=>e.FKCardTagID==u.CardID)
select new CardModel {
cardHashCode = tag.tagName,
cardDate = u.CardDate,
cardFileName = u.CardFileName,
cardFilePath = u.CardFilePath,
cardID = u.CardID,
cardTitle = u.CardTitle
}).ToList();
if (cardlist.Count == 0) {
return Json(new { success = false });
}
else {
return PartialView("_FunHomePartial", cardlist);
}
}
其中tag=>tagName
的匹配将来自列表cardtaglist
。
我在行中得到Cannot implicitly convert type int to bool
错误-
where u.CardID == cardtaglist.Where(e=>e.FKCardTagID==u.CardID)
如何匹配列表cardtaglist
中的元素?
如何替换
u.CardID == cardtaglist.Where(e=>e.FKCardTagID==u.CardID)
跟
cardtaglist.Any(e=>e.FKCardTagID==u.CardID)
首先,如果您只使用 FKCardTagID
,为什么选择所有实体CardTagTable
!最佳方法 - 仅选择必填字段:
var cardtagIds = (from u in db.CardTagTables
where u.CardTagName == tag.tagName
select u.FKCardTagID).ToList();
关于您的错误,您正在将IQueriable与数值进行比较。在这种情况下,您可以使用Contains
方法:
cardlist = (from u in db.CardTables.Where(u => cardtagIds.Contains(u.CardID));
select new CardModel {
....
编辑
此外,还可以优化此查询:
cardlist = (from u in db.CardTables.Where(u =>
db.CardTagTables
.Where(ct => ct.CardTagName == tag.tagName)
.Select(ct => ct.FKCardTagID)
.Contains(u.CardID))
select new CardModel {
....
使用:
var result=cardtaglist.Any(e=>e.FKCardTagID==u.CardID)