添加第3个类,其中2个类是linq查询的子项,最终显示为json

时间:2016-03-24 20:32:25

标签: c# json linq

此问题基于

Data in Linq query not in join is not in output to json only those that are related in 2 classes are showing up

这个答案DID正常工作

但是,我添加了一个我要分组的第3课" item"

var query = 
from d in reportData
join r in reportDefinition on d.ReportGroupId equals r.ReportGroupId into items
select new
{
    d.ReportGroupName,
    items = items.ToList(),
    d.ReportGroupId
};

新更新的dotnetfiddle https://dotnetfiddle.net/IIBFKG

如何在CustomReportDefinition类中添加以显示在项目或ReportData中?

1 个答案:

答案 0 :(得分:0)

实际上,您可以使用完全相同的模式添加任意数量的类:

var query = from d in reportData
            join r in reportDefinition on d.ReportGroupId equals r.ReportGroupId into items
            join cr in customReportDefinition on d.ReportGroupId equals cr.ReportGroupId into customItems
            select new
            {
                d.ReportGroupName,
                items = items.ToList(),
                customItems = customItems.ToList(),
                d.ReportGroupId
            };

更新:根据您的评论,您希望整合itemscustomItems。看看以下内容是否适合您:

var query = from d in reportData
            join r in reportDefinition on d.ReportGroupId equals r.ReportGroupId into items
            join cr in customReportDefinition on d.ReportGroupId equals cr.ReportGroupId into customItems
            select new
            {
                d.ReportGroupName,
                items = items.Select(r => new
                {
                    r.Id, r.ReportGroupNameDef, r.SortOrder, r.ReportGroupId, r.Type
                }).Concat(customItems.Select(cr => new
                {
                    cr.Id, cr.ReportGroupNameDef, cr.SortOrder, cr.ReportGroupId, cr.Type
                })).ToList(),
                d.ReportGroupId
            };