Flattenning a collection of Entities - a common task ...

Public forum to share code snippets, screen shorts, experiences, etc.
Post Reply
User avatar
Phil Hepburn
Posts: 743
Joined: Sun Sep 11, 2016 2:16 pm

Flattenning a collection of Entities - a common task ...

Post by Phil Hepburn »

Hi guys,

Here is a new way to solve an old and common data problem.

How to 'flatten' the data of an existing data structure - say a collection of Customer objects.

Lets say our Customer objects have a property which is a collection of Orders, and then the Order objects each have a property which is a collection of OrderLine objects.

Our task is, how do we 'get at' the OrderLine details starting with the bunch of customers.

Well, if all we need is a long list (collection) of OrderLine property values, then this first image does the trick :-
Flatten_04.jpg
Flatten_04.jpg (134.27 KiB) Viewed 257 times
The 'SelectMany' extension method comes in VERY handy indeed. Each time I use a 'SelectMany' we lose a nested level - so three levels become one.

Now then, the next image show code which may frighten (or worry) some guys - BUT - in fact most of the textual detail is about specifying the properties to be included in the 'data select'. There is also a bit of extra 'confusion' created by an 'OrderBy' clause and a 'Where' clause.

Lets have a look first before we have a sort discussion :-
Flatten_01.jpg
Flatten_01.jpg (36.54 KiB) Viewed 257 times
And to go along with the code, the GUI display details below :-
Flatten_02.jpg
Flatten_02.jpg (50.87 KiB) Viewed 257 times
Flatten_03.jpg
Flatten_03.jpg (87.34 KiB) Viewed 257 times
I had to split the GUI display for deeper technical reasons we won't bother with here.

The data display should show that we have flattened the data, so we have Customer fields along with Order fields as well as OrderLine fields. Its up to us to select and choose.

In a way we have de-normalised the data.

After a few tries, and some testing, it is not as difficult as it looks to do this data flattening.

If we are to work more with Entities in our business solutions, then we are more likely to need to flatten data in our projects. What is shown here should do (serve) most of us for most of our problems.

Yes, the above is using the Extension Method approach of LINQ.

Nick Friend is right as usual, it is easier when you just give it a try - Lambdas get easier to follow, and easier to write.

Hope this interests a few - some or all of this will be available in Cologne at the end of April. Have you registered yet?

Best regards,
Phil.
Wales, UK.
Post Reply