你想知道一个组件中是否存在给定类型的组件吗?
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 },
};