带有linq lambda表达式的查询列表
本文关键字:查询 列表 表达式 linq lambda 带有 | 更新日期: 2023-09-27 18:20:12
如何获得县列表中的参与者?我得到var县中的县,然后我想得到所有在县列表中有CountyOfParticipationId的参与者。
if (collaborationId != null)
{
var counties = (from c in db.CountyCollaborations
where c.CollaborationId == collaborationId
select c).ToList();
participants = participants.Where(p => p.CountyOfParticipationId in counties);
}
.Where(p => counties.Contains(p.CountyOfParticipationId))
现在,如果有很多数据,请小心其复杂性。列表中的Contains
是O(n),因此总体上算法是O(n*m),其中n,m是参与者的#和县的#。
为了获得更好的性能,您可以将郡存储在HashSet中,该HashSet具有O(1)Contains,即总体O(n)。
当然,如果县的数量很小,那也没关系。
EDIT:刚刚注意到您的列表不包含id,而是包含完整的对象。为了使上面的代码正常工作,您还需要将linq查询从select c
更改为select c.Id
或类似的内容(不知道字段的名称)。
participants = participants
.Where(p => counties.Any(c=> c.CountyId == p.CountyOfParticipationId) )
或
participants.Where(p => p.County.CollaborationId == collaborationId)
如果您已经正确设置了关系,也应该工作
这在某些情况下可能会更好,因为如果linq方法在场景后面将表达式转换为sql,则不必单独存储郡。
participants = (from p in participants
join c in
db.CountyCollaborations
.Where(cty=>cty.CollaborationId == collaborationId)
on p.CountyOfParticipationId equals c.CountyId
select p);
假设每个县都有一个CountyId:
participants = participants.Where( p =>
counties.Select(c=> c.CountyId ).Contains( p.CountyOfParticipationId) );