C#-展开具有嵌套对象集合的LINQ集合对象(Flatten LINQ collection object with nested object collections)

展开具有嵌套对象集合的LINQ集合对象(Flatten LINQ collection object with nested object collections)

 858  2016-10-11  IT屋

 

百度翻译此文   有道翻译此文

问 题

 

This is a tricky one. I an trying to flatten a LINQ object collection. Each item in the collection has the potential of having two collections of other objects. See the example below.

public class DemoClass
{
    public string Name {get; set;}
    public string Address {get; set;}
    public List<Foo> Foos = new List<Foo>();
    public List<Bar> Bars = new List<Bars>();
}

What I had been doing is this using this code block to flatten this object

var output = from d in DemoClassCollection
    from f in d.Foos
    from b in d.Bars
    select new {
        d.Name, 
        d.Address,
        f.FooField1, 
        f.FooField2, 
        b.BarField1,
        b.BarField2
    };

But the problem I'm having is that the result I get is only those DemoClass objects that have objects in the Foos and Bars collections. I need to get all objects in the DemoClass regardless if there are objects in the Foos and Bars collections.

Any help would be greatly appreciated.

Thanks!

解决方案

Sounds like you might want to use DefaultIfEmpty:

var output = from d in DemoClassCollection
    from f in d.Foos.DefaultIfEmpty()
    from b in d.Bars.DefaultIfEmpty()
    select new {
        d.Name, 
        d.Address,
        FooField1 = f == null ? null : f.FooField1, 
        FooField2 = f == null ? null : f.FooField2, 
        BarField1 = b == null ? null : b.BarField1, 
        BarField2 = b == null ? null : b.BarField2
    };

本文地址:IT屋 » 展开具有嵌套对象集合的LINQ集合对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值