4

我将如何获得县列表中的参与者?我得到了 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);


}
4

4 回答 4

3

.Where(p => counties.Contains(p.CountyOfParticipationId))

现在,如果有很多数据,请注意其复杂性。Contains在一个列表中是 O(n),所以总体而言算法是 O(n*m),其中 n,m 是参与者的数量和县的数量。

为了获得更好的性能,您可以将县存储在具有 O(1) 包含的 HashSet 中,这意味着总体上是 O(n)。

当然,如果县的数量很少,那也没关系,真的。

编辑:刚刚注意到您的列表不包含 ID,而是包含完整对象。要使上面的代码正常工作,您还需要将 linq 查询从select ctoselect c.Id或类似的东西更改(不知道该字段的名称)。

于 2013-06-26T20:53:50.210 回答
3
participants = participants
.Where(p => counties.Any(c=> c.CountyId == p.CountyOfParticipationId) )

或者

participants.Where(p => p.County.CollaborationId == collaborationId)

如果您已正确建立关系,也应该可以工作

于 2013-06-26T20:50:50.880 回答
1

这在某些情况下可能会更好,因为如果 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);
于 2013-06-26T21:12:51.350 回答
0

假设每个县都有一个 CountyId:

participants = participants.Where( p => 
  counties.Select(c=> c.CountyId ).Contains( p.CountyOfParticipationId) );
于 2013-06-26T20:51:33.353 回答