2011-03-20 36 views
1

我有一個foreach在foreach中,我很樂意將它轉換爲LINQ。如果它只是1 foreach我可以使用一個地方,但我很困惑..這是我的代碼,任何幫助真的很感激。LINQ:幫忙轉換LINQ的foreach中的foreach - 如果可能的話

基本上我需要找到發票,但它取決於2級下的元數據。我認爲代碼是不言自明的。

currentMetaData >>> Is created outside of the foreach code 
its 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; 
    } 
    } 
} 

我真的很想用LINQ縮短它。這可能嗎?

回答

1

這將給所有的名字

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

只有第一個值模擬break;聲明在現有的循環。

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

好東西..謝謝! ..我想它不可能轉換爲LAMBDAs,因爲有2個Froms?那是對的嗎? – Martin 2011-03-20 08:37:19

+0

@Martin:不,你可以用SelectMany調用來使用lambda表單。 – 2011-03-20 08:40:10

+0

你爲什麼在這裏調用'ToList'?這不會做任何有用的事情 - 事實上,它消除了使用First的一部分(即在您到達第一個元素後立即停止評估查詢)。 – 2011-03-20 08:41:09