linq嵌套列表包含
我有一个问题,你在那里的linq专家! 在组件实例的嵌套列表中,我需要知道其中是否存在特定类型的组件。 可以用linq来表达吗? 考虑到可能有application.Components [0] .Components [0] .Components [0] …我的问题是面向linq中的递归查询!
我给你留下实体让你对模型有所了解。
public class Application { public List Components { get; set; } } public class Component { public ComponentType Type { get; set; } public List Components { get; set; } } public enum ComponentType { WindowsService, WebApplication, WebService, ComponentGroup }
您想知道组件中的任何组件是否属于给定类型?
var webType = ComponentType.WebApplication; IEnumerable webApps = from c in components from innerComp in c.Components where innerComp.Type == webType; bool anyWebApp = webApps.Any();
那么innercomp.components呢?
编辑 :所以你想要不仅在顶层或二层递归地找到给定类型的组件。 然后您可以使用以下Traverse
扩展方法:
public static IEnumerable Traverse (this IEnumerable source, Func> fnRecurse) { foreach (T item in source) { yield return item; IEnumerable seqRecurse = fnRecurse(item); if (seqRecurse != null) { foreach (T itemRecurse in Traverse(seqRecurse, fnRecurse)) { yield return itemRecurse; } } } }
以这种方式使用:
var webType = ComponentType.WebApplication; IEnumerable webApps = components.Traverse(c => c.Components) .Where(c => c.Type == webType); bool anyWebApp = webApps.Any();
样本数据:
var components = new List() { new Component(){ Type=ComponentType.WebService,Components=null }, new Component(){ Type=ComponentType.WebService,Components=new List (){ 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 (){ new Component(){ Type=ComponentType.WebService,Components=new List (){ 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( );