Skip to main content
edited title
Link
user1228
user1228

C# and LINQ :: Flatten LINQ collection object with nested object collections

Source Link
Andy Evans
  • 7.2k
  • 19
  • 77
  • 119

C# and LINQ :: Flatten LINQ collection object with nested object collections

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!