在Linq中展平和分组复杂对象并保留空子项

时间:2018-03-28 18:56:02

标签: c# linq

我有一个名为RouteExport的复杂对象列表,我试图根据CustomerNumber值展平和分组,以便返回一个看起来像

的匿名对象
{ CustomerNumber = "1235", Route = route1, Section = section2, Sequence = sequence2 } 

{ CustomerNumber = "1234", Route = route1, Section = null, Sequence = null }

模型看起来像这样:

public class RouteExport
{
    public string Name { get; set; }
    public string Term { get; set; }
    public List<string> CustomerNumbers { get; set; }
    public List<SectionExport> Sections { get; set; }
}

public class SectionExport
{
    public string Name { get; set; }
    public List<string> CustomerNumbers { get; set; }
    public List<SequenceExport> Sequences { get; set; }
}

public class SequenceExport
{
    public string Name { get; set; }
    public List<string> CustomerNumbers { get; set; }
}

每个对象都有一个CustomerNumber列表,如果他们在该路由/部分/序列中,则该列表包含客户编号。我想根据该客户编号对每个对象进行分组。到目前为止,我一直在使用它:

var flattendExport = exportViewModel.ExportContainer.Routes
            .SelectMany(rt => rt.Sections
                .SelectMany(sec => sec.Sequences
                    .SelectMany(seq => seq.CustomerNumbers
                        .Select(custNum => new { rt, sec, seq, custNum })))).ToList();

使对象变平,但不按CustomerNumber分组,也不为段或序列返回null。

如何创建一个返回按每个对象CustomerNumbers分组的展平列表的查询,如果它们不在某个部分或序列中,则返回null

使用测试用例进行更新

我没有充分说明原始问题所以进行了一些编辑。我想根据客户的号码分组这样的数据:

var data = new List<RouteExport>
{
    new RouteExport
    {
        CustomerNumbers = new List<string> { "1", "2" },
        Sections = new List<SectionExport>
        {
            new SectionExport()
            {
                CustomerNumbers = new List<string> { "1" },
                Sequences = new List<SequenceExport> {
                    new SequenceExport()
                    {
                        CustomerNumbers = new List<string> { "1" }
                    }
                }
            }
        }
    }
};

返回以下结果:

{ CustomerNumber = "1", Route = route1, Section = section1, Sequence = sequence1},
{ CustomerNumber = "2", Route = route1, Section = null, Sequence = null}

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ&#39; DefaultIfEmpty插入Sections集合为空时所需的空值。见https://msdn.microsoft.com/en-us/library/bb355419(v=vs.110).aspx

在第二个.SelectMany(...)的末尾添加:

.DefaultIfEmpty(new { rt, null, null, cystNum })

对于没有任何部分的每条路线,它会做什么,并创建一个虚拟结果&#39;。

编辑:鉴于您更改的要求,它将如下所示:

 var res = data.SelectMany(r => r.CustomerNumbers
            .SelectMany(c => r.Sections.Where(s => s.CustomerNumbers.Contains(c))
                .SelectMany(s => s.Sequences
                  .Select(seq => new { CustomerNumber = c, Route = r, Section = s, Sequence = seq }))
                .DefaultIfEmpty(new { CustomerNumber = c, Route = r, Section = (SectionExport)null, Sequence = (SequenceExport)null })))
                .ToList();