Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query list with linq lambda expressions

Tags:

c#

linq

How would I get participants that are in a list of counties? I get the counties in var counties, then I want to get all of the participants that have a CountyOfParticipationId that is in the list of counties.

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);


}
like image 583
user1202606 Avatar asked Mar 23 '23 09:03

user1202606


2 Answers

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

Now if there's a lot of data be careful with the complexity of this. Contains in a list is O(n), so overall the algorithm is O(n*m) with n,m being the # of participants and the # of counties.

For better performance you could store the counties in a HashSet, which has O(1) Contains, meaning O(n) overall.

Of course if the number of counties is small it doesn't matter, really.

EDIT: Just noted that your list doesn't contain the ids but full objects. For the code above to work you also need to change your linq query from select c to select c.Id or something like that (don't know the name of the field).

like image 69
jods Avatar answered Mar 26 '23 00:03

jods


participants = participants
.Where(p => counties.Any(c=> c.CountyId == p.CountyOfParticipationId) )

Or

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

should also work if you have set up relations properly

like image 20
AD.Net Avatar answered Mar 26 '23 00:03

AD.Net