c# - 如何为嵌套集合编写 Linq 或 Lambda 表达式

标签 c# linq lambda nested

我知道简单的 linq,但这里的问题陈述有多层嵌套。如何为嵌套集合编写 Linq 或 Lambda 表达式。

输入对象定义:

public class Service
{
    public string Name { get; set; }
    public List<Service> ChildServices{ get; set; }

    public List<Action> AvailableActions{ get; set; }
}

public class Action
{
    public string Name { get; set; }
    public List<string> Parameters{ get; set; }

    public void Execute()
    {
        ...
    }
}

嵌套可以多级

Linq 预期输出

这里我需要写Linq或Lambda表达式

  1. 获取所有服务
  2. 获取给定名称的服务

最佳答案

如果我们可以假设您从服务列表开始,如下所示:

var services = new List<Service>()
{
    new Service()
    {
        Name = "A",
        ChildServices = new List<Service>()
        {
            new Service() { Name = "C", ChildServices = new List<Service>() },
            new Service()
            {
                Name = "D",
                ChildServices = new List<Service>()
                {
                    new Service() { Name = "E", ChildServices = new List<Service>() },
                    new Service() { Name = "F", ChildServices = new List<Service>() },
                }
            },
        }
    },
    new Service()
    {
        Name = "B",
        ChildServices = new List<Service>()
        {
            new Service() { Name = "G", ChildServices = new List<Service>() },
            new Service() { Name = "H", ChildServices = new List<Service>() },
        }
    },
};

看起来像这样:

services

然后这个查询会将列表展平:

Func<IEnumerable<Service>, IEnumerable<Service>> traverse = null;
traverse = ss =>
    from s in ss
    from s2 in new [] { s }.Concat(traverse(s.ChildServices))
    select s2;

调用 traverse(services) 返回:

flattened

然后您可以使用普通的 LINQ 查询按名称查找服务,或者您可以像这样创建一个字典:

var serviceByName = traverse(services).ToDictionary(x => x.Name);

var serviceG = serviceByName["G"];

关于c# - 如何为嵌套集合编写 Linq 或 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30043579/

相关文章:

c# - 有谁知道任何进行音频合成器仿真的 C/C++/C# 代码库?

c# - .NET 程序集中的 Fusion 是什么

c# - 使用 LINQ 删除重复记录

c# - 如何将 GridView 绑定(bind)到复杂对象

c++ - 标准是否保证无捕获 lambda 为空?

lambda - 如何在 lambda 过滤器中使用多个声明?

java - Java 是否具有与 C# 的元组等效的变量类型?

c# - 没有可用的连接来服务此操作 - Redis 与 StackExchange.Redis

c# - 使用 Linq to SQL 简化创建数组列

c++ - 在静态函数的 lambda 中捕获相当于 'this' 的值