繁体   English   中英

Linq 嵌套在 c# 中

[英]Nested Linq in c#

我想使用 linq 作为树结构提取一个列表。

{
    "details": [
        {
            "description":"This is description 1",
            "Name": "Name 1"
        },
        {
            "description":"This is description 2",
            "Name": "Name 2"
        }
    ],
    "price": 100
}

我手头有一个 detailsDto 作为 List<>,我将在 Details 字段中使用它

来自“m”实例的属性将在 detailsDto 中绑定。 那就是我面临如何去做的问题。 “m”实例中可用的描述和名称字段

var data = await Task.FromResult((
    from c in _context.C
    join mc in _context.MC on c.VId equals mc.VId
    join m in _context.M on mc.Id equals m.mcId
    where mc.Id == mcId && c.Id == CId
    select new MainDto()
    {
        Price = mc.Price,
        // Details =
    }
    ).FirstOrDefault()
);

可能你需要这个查询:

var data = await (
    from c in _context.C
    join mc in _context.MC on c.VId equals mc.VId
    where mc.Id == mcId && c.Id == CId
    select new MainDto()
    {
        Price = mc.Price,
        Details = _context.M.Select(m => new DetailsDto 
        {
            Name = m.Name,
            description = m.Description,
        }).ToList()
    }
    ).FirstOrDefaultAsync();

这应该有帮助

{
    Price = mc.Price,
    Details = m.Select(x => new DetailDto
    {
        Description = x.Description,
        Name = x.Name
    }).ToList()
}

它将为m列表中的每个元素创建一个DetailDto class 的新实例,并将DescriptionName属性的值分配给DetailDto实例中的相应属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM