2010-07-16 49 views
1

希望我可以解釋這到它有意義的地方,但我試圖使用一個特殊和複雜(至少對我來說是複雜的)標準集來從主列表中獲得對象列表。LINQ to Entities問題 - 子集合中所有項目出現在另一個集合中的所有對象?

我有一個名爲TableInfo的類,公開了ForeignKeyInfo列表。 ForeignKeyInfo有一個名爲Table的字符串屬性(等等)。我需要使用TableInfo對象進行一些順序處理,但只能處理尚未處理的TableInfo對象。爲了跟蹤哪些TableInfo對象已經被處理,我有一個List,它在處理完成後存儲表的名字。

我想循環直到我的TableInfo集合中的所有項目出現在我的處理列表中。對於循環的每次迭代,我都應該處理所有的TableInfo項目,其中所有ForeignKeyInfo.Table字符串出現在我處理的列表中。

下面是我如何「標準」循環的代碼寫它:

while(processed.Count != _tables.Count) 
{ 
    List<TableInfo> thisIteration = new List<TableInfo>(); 

    foreach (TableInfo tab in _tables) 
    { 
      bool allFound = true; 
      foreach (ForeignKeyInfo fk in tab.ForeignKeys) 
      { 
       allFound = allFound && processed.Contains(fk.Table); 
      } 

      if (allFound && !processed.Contains(tab.Name)) 
      { 
       thisIteration.Add(tab); 
      } 
    } 

    //now do processing using thisIteration list 
    //variable, "thisIteration", is what I'd like to replace with the result from LINQ 
} 

回答

1

這應做到:

var thisIteration = _tables.Where(t => !processed.Contains(t.Name) 
            && t.ForeignKeys 
             .All(fk => processed.Contains(fk.Table)); 

我假設你只需要遍歷thisIteration集合,在這種情況下將其作爲IEnumerable保留就可以了。如果你需要它是一個列表,你可以在末尾放一個.ToList()呼叫。

+0

完美!謝謝! – 2010-07-16 19:47:33

+0

不客氣! :) – tzaman 2010-07-16 19:48:53

0

我真的不知道你想在這裏做什麼。但是,您可以將循環體轉換成以下LINQ查詢,如果讓事情變得更簡單...

List<TableInfo> thisIteration = (from tab in _tables 
           let allFound = tab.ForeignKeys.Aggregate(true, (current, fk) => current && processed.Contains(fk.Table)) 
           where allFound && !processed.Contains(tab.Name) 
           select tab).ToList(); 
相關問題