Can I export hierarchical data to Excel?
If I have a query that returns a collection as one of its columns, such as...
Customers.Select(c => new {
c.Name,
c.Orders.Select(o => o.OrderDate)
})
...and I want to export this to Excel so that I get rows like the following...
Jim Spriggs | 1st Jan '16
Jim Spriggs | 21st Mar '16
Fred Ferret | 12th Apr '16
...can I do this? If my data set includes a collection, then exporting to Excel ignores the column. I tried adding new line characters between the dates in the hope that it would produce something like this...
Jim Spriggs | 1st Jan '16
| 21st Mar '16
Fred Ferret | 12th Apr '16
...but it didn't help, the order dates were all in one cell on one line.
Any ideas? Thanks in advance.
Customers.Select(c => new {
c.Name,
c.Orders.Select(o => o.OrderDate)
})
...and I want to export this to Excel so that I get rows like the following...
Jim Spriggs | 1st Jan '16
Jim Spriggs | 21st Mar '16
Fred Ferret | 12th Apr '16
...can I do this? If my data set includes a collection, then exporting to Excel ignores the column. I tried adding new line characters between the dates in the hope that it would produce something like this...
Jim Spriggs | 1st Jan '16
| 21st Mar '16
Fred Ferret | 12th Apr '16
...but it didn't help, the order dates were all in one cell on one line.
Any ideas? Thanks in advance.
Comments
You could try something like
Customers.Select(c => new { Orders = c.Orders.Select(o => new { c.Name, o.OrderDate} ) } ).SelectMany(r=>r.Orders);
Please explain if I missed the point. Thanks for the reply.
The example provided by sgmoore does exactly what you need.
I'd prefer the LINQ query syntax, which is a bit simpler and easier to read:
I prefer the method syntax, as I find it much easier to read, especially when used with extension methods
Thanks for the reply
Then try this: Method syntax: If you're using LINQ-to-objects, use
o?.OrderDate
to eliminate null reference exceptions.Thanks again
This will display the customer name only on the first row (where order index is zero) Method syntax: The .AsEnumerable() is necessary to support the overload function .Select((T x, int i) => expr) function and will generate a lot of requests to the server, but the output should satisfy your needs