我正在尝试从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
中的元素?
答案 0 :(得分:1)
如何更换
u.CardID == cardtaglist.Where(e=>e.FKCardTagID==u.CardID)
带
cardtaglist.Any(e=>e.FKCardTagID==u.CardID)
答案 1 :(得分:1)
首先,如果您只使用CardTagTable
,为什么选择所有FKCardTagID
实体!?最好的方法 - 只选择必填字段:
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 {
....
答案 2 :(得分:0)
使用:
var result=cardtaglist.Any(e=>e.FKCardTagID==u.CardID)