Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract list where string is contained inside a list inside the list

Tags:

c#

linq

Basically I have a list of objects. Let's call them meetings. Inside the meetings there is another list of objects. Let's call those participants. I want to return all meetings where a certain participant is in the list.

I want something like this:

meetings.Where(meeting => meeting.Participants.Name == "Test name").ToList();

Basically return a list of meetings, where the meeting has a participant with the name "Test name".

EDIT: I actually ended up using a MongoDB filter. Before I would just extract all the "meetings" (with a filter) and then use LINQ to filter the list. Might as well filter out the results on database level.. But this is good to know.

like image 549
MortenMoulder Avatar asked Sep 26 '16 09:09

MortenMoulder


2 Answers

Are you looking for Any?

var result = meetings
  .Where(meeting => meeting
     .Participants
     .Any(participant => participant.Name == "Test name"))
  .ToList();
like image 112
Dmitry Bychenko Avatar answered Nov 04 '22 22:11

Dmitry Bychenko


You can use LINQ method Any and this one line of code :

var result = meetings.Where(m => m.Participants.Any(p => p.Name == "Test name")).ToList();
like image 3
Fabjan Avatar answered Nov 04 '22 20:11

Fabjan