2012-09-07 143 views
6

我有一個問題,你linq專家在那裏! 在組件實例的嵌套列表中,我需要知道是否存在特定類型的組件。它可以用linq表示嗎?考慮到有可能是application.Components [0] .Components [0] .Components [0] ...我的問題是面向linq遞歸查詢!linq嵌套列表包含

我給你留下實體讓你對模型有一些瞭解。

public class Application 
{ 
    public List<Component> Components { get; set; } 
} 

public class Component 
{ 
    public ComponentType Type { get; set; } 
    public List<Component> Components { get; set; } 
} 

public enum ComponentType 
{ 
    WindowsService, 
    WebApplication, 
    WebService, 
    ComponentGroup 
} 

回答

5

你想知道,如果在任何一個組件的組件是給定類型的?

var webType = ComponentType.WebApplication; 
IEnumerable<Component> webApps = from c in components 
           from innerComp in c.Components 
           where innerComp.Type == webType; 
bool anyWebApp = webApps.Any(); 

什麼innercomp.components?

編輯:所以,你想找到遞歸不僅在頂部或第二級給定類型的組件。然後你可以使用以下Traverse擴展方法:

public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> fnRecurse) 
{ 
    foreach (T item in source) 
    { 
     yield return item; 

     IEnumerable<T> seqRecurse = fnRecurse(item); 
     if (seqRecurse != null) 
     { 
      foreach (T itemRecurse in Traverse(seqRecurse, fnRecurse)) 
      { 
       yield return itemRecurse; 
      } 
     } 
    } 
} 

以這種方式使用:

var webType = ComponentType.WebApplication; 
IEnumerable<Component> webApps = components.Traverse(c => c.Components) 
           .Where(c => c.Type == webType); 
bool anyWebApp = webApps.Any(); 

樣本數據:

var components = new List<Component>() { 
    new Component(){ Type=ComponentType.WebService,Components=null }, 
    new Component(){ Type=ComponentType.WebService,Components=new List<Component>(){ 
     new Component(){ Type=ComponentType.WebService,Components=null }, 
     new Component(){ Type=ComponentType.ComponentGroup,Components=null }, 
     new Component(){ Type=ComponentType.WindowsService,Components=null }, 
    } }, 
    new Component(){ Type=ComponentType.WebService,Components=null }, 
    new Component(){ Type=ComponentType.WebService,Components=new List<Component>(){ 
     new Component(){ Type=ComponentType.WebService,Components=new List<Component>(){ 
      new Component(){Type=ComponentType.WebApplication,Components=null} 
     } }, 
     new Component(){ Type=ComponentType.WindowsService,Components=null }, 
     new Component(){ Type=ComponentType.WebService,Components=null }, 
    } }, 
    new Component(){ Type=ComponentType.WebService,Components=null }, 
    new Component(){ Type=ComponentType.ComponentGroup,Components=null }, 
    new Component(){ Type=ComponentType.WebService,Components=null }, 
}; 
+0

innercomp.components呢? –

+0

@IrrationalRationalWorks:編輯我的答案。 –

+0

我正在吃彩虹...讓我檢查 –

1
if(Components.Any(c => c.Type == ComponentType.WindowsService)) 
{ 
    // do something 
} 

,或者你可以做

var listContainsAtLeastOneService = 
    (from c in Components 
     where c.Type == ComponentType.WindowsService 
     select c).Any(); 
+0

什麼c.components? –