-2

Can someone help?

I tried to create a Linq but don't find the right syntax:

This is the code I want to update to Linq:

List<Person> list = new List<Person>();
foreach (Person p in persons)
{
   foreach (Course c in p.courses)
   {
      if (c.id == q.id)
      {
         list.Add(p);
      }
   }
}

1 Answers1

4

You're looking for SelectMany that will allow you to flatten the inner collection.

var list = persons
    .SelectMany(p => p.cources.Where(c => c.id == q.id).Select(_ => p))
    .ToList();

This will filter the inner courses by the id and repeat the same person for each match and then flatten all those into a list. However it seems like you'd only want to add a person to the list once in which case you'd actually want

var list = persons
    .Where(p => p.cources.Any(c => c.id == q.id))
    .ToList();
juharr
  • 31,741
  • 4
  • 58
  • 93
  • @JohnathanBarclay Yeah, I've fixed that and included what is likely the actual query they want instead of the one that does exactly what they are currently doing. – juharr May 12 '20 at 13:52