展开具有嵌套对象集合的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集合对象