Search code examples
linqlinq-to-sqlforeachlinq-to-objectswhere-clause

How to convert a foreach within a foreach to LINQ, if it's possible


I have a foreach that is within a foreach and I would love to convert it to LINQ. If it was just 1 foreach I could use a Where but I am confused. Here is my code.

Basically I need to find the invoice but it depends on metadata which is 2 levels down. I think the code is self-explanatory.

currentMetaData >>> Is created outside of the foreach code 
It's an object, but the code below works.

foreach (var item in this.invoices.Items)
{
  foreach (var metaData in item.MetaDatas)
  {
    if (metaData == currentMetaData)
    {
      name = item.Name;
      break;
    }
  }
}

I would love to shorten it with LINQ. Is this possible?


Solution

  • This would give all the names

     var name = 
                 from i in this.invoices
                 from m in i.Metadata
                 where m == currentMetadata
                 select i.Name;
    

    Only First Value to simulate the break; statement in your existing loop.

     string name = 
                 (from i in this.invoices
                 from m in i.Metadata
                 where m == currentMetadata
                 select i.Name).First();