c# – linq嵌套列表包含

c# – linq嵌套列表包含,第1张

概述我有一个问题,你在那里 linq专家! 在组件实例的嵌套列表中,我需要知道其中是否存在特定类型的组件.可以用linq表达吗?考虑到可能有application.Components [0] .Components [0] .Components [0] …我的问题是面向linq中的递归查询! 我告诉你实体让你对模型有所了解. public class Application{ publi 我有一个问题,你在那里 linq专家!
在组件实例的嵌套列表中,我需要知道其中是否存在特定类型的组件.可以用linq表达吗?考虑到可能有application.Components [0] .Components [0] .Components [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();

what about 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,new Component(){ Type=ComponentType.ComponentGroup,new Component(){ Type=ComponentType.windowsService,} },Components=new List<Component>(){            new Component(){Type=ComponentType.WebApplication,Components=null}        } },};
总结

以上是内存溢出为你收集整理的c# – linq嵌套列表包含全部内容,希望文章能够帮你解决c# – linq嵌套列表包含所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1251199.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存