List of queries with lambda linq expressions

How do I get members who are on the county list? I get counties in var counties, then I want to get all the members who have CountyOfParticipationId, which is on the counties list.

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
source share
4 answers

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

Now, if there is a lot of data, be careful with the complexity of this. Contains in the list O (n), therefore, in general, the algorithm is O (n * m), where n, m are # participants and # districts.

For best performance, you can save the counties in a HashSet that contains O (1), which means O (n) as a whole.

Of course, if the number of counties is small, it does not matter, really.

EDIT . Just noted that your list does not contain identifiers, but complete objects. In order for the above code to work, you also need to change your linq query from select c to select c.Id or something like this (I don't know the name of the field).

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

Or

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

should also work if you set up the relationship correctly

+3
source

In some situations, this may be better, since you will not need to copy the counties separately if the linq method translates the expression into sql for the values.

 participants = (from p in participants join c in db.CountyCollaborations .Where(cty=>cty.CollaborationId == collaborationId) on p.CountyOfParticipationId equals c.CountyId select p); 
+1
source

Assuming there is CountyId in every county:

 participants = participants.Where( p => counties.Select(c=> c.CountyId ).Contains( p.CountyOfParticipationId) ); 
0
source

Source: https://habr.com/ru/post/1488373/


All Articles