我有一个问题要问你们linq专家!在组件实例的嵌套列表中,我需要知道其中是否有特定类型的组件。它可以用linq表示吗?考虑到可能会有申请。组件[0]。组件[0]。组件[0]。。。我的问题是针对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
}
您想知道组件中是否有任何组件属于给定类型吗?
var webType = ComponentType.WebApplication;
IEnumerable<Component> webApps = from c in components
from innerComp in c.Components
where innerComp.Type == webType;
bool anyWebApp = webApps.Any();
内部组件呢?
编辑:因此,您希望递归地查找给定类型的组件,而不仅仅是在顶级或第二级。然后您可以使用以下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 },
};
if( Components.Any( c => c.Type == ComponentType.WindowsService ) )
{
// do something
}
或者你可以做
var listContainsAtLeastOneService =
( from c in Components
where c.Type == ComponentType.WindowsService
select c ).Any( );