Welcome, Guest
Username: Password: Remember me
Share your code snippets, screen shots etc. here
  • Page:
  • 1

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

Flattenning a collection of Entities - a common task ... 2 years 3 weeks ago #1

  • Phil Hepburn
  • Phil Hepburn's Avatar Topic Author
  • Offline
  • Posts: 737
  • Karma: 7
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 :-

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 :-

And to go along with the code, the GUI display details below :-

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,
Wales, UK.

Please Log in or Create an account to join the conversation.

  • Page:
  • 1