[英]linq - find item in list within multiple lists
我有一个高度嵌套的课程,试图找到一个埋在其中的物品。 以下内容给我一个错误“无法将类型匹配转换为布尔值”,尽管我不明白为什么它认为我正在尝试返回布尔值。
var match = community.TeamLeagues
.Where(x => x.Seasons
.Where(y => y.Divisions
.Where(z => z.Matches
.Where(a => a.Id == "1234").FirstOrDefault())));
Where
本身返回(递延)可枚举的项目,因此不能由外部Where
用作条件。 您可能想要做的是在外部Where
内使用Contains()
, Any()
或All()
,这将返回您要查找的结果。
这样的事情可能就是您想要的:
var match = community.TeamLeagues.Where(t =>
t.Seasons.Any(
s => s.Divisions.Any(
d => d.Matches.Any(
m => m.Id == "1234")
)));
Where
方法需要评估返回bool
的表达式。 您的嵌套Where
不这样做-唯一的Where是最后一个a => a.Id == "1234"
,所有其他表达式都返回IEnumerable
。
z.Matches.Where(a => a.Id == "1234").FirstOrDefault()
返回Match
类型的对象(您的IEnumerable Matches
集合项类型)(或为null),没有布尔值。 我猜您需要检查匹配项中是否有ID为1234的整数。请使用Any
评估条件:
var match = community.TeamLeagues.Where(x =>
x.Seasons.Any(y =>
y.Divisions.Any(z =>
z.Matches.Any(a => a.Id == "1234")
)));
[ items.Where(x => x.Id == 4).Any()
与items.Any(x => x.Id == 4)
]
这将返回所有包含Season的TeamLeague,其中的Season的Division的Match的ID为1234。
为了简单起见,您还可以直接使用Matches
表,并使用ViewModel可以表示您的视图。
例如:var MyViewModel =(从Math中的l,其中l.Id ==“ 1234”选择新的MyViewModel {ID = l.Id,MatchName = l.Name,})。ToList();
无法使其与linq一起使用,但可以与查询语法一起使用。
var leagueMatch = (from teamLeague in community.TeamLeagues
from season in teamLeague.Seasons
from division in season.Divisions
from match in division.Matches.Where(x => x.Id == "1234")
select match).FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.