SelectMany and Include: The Love Story That Ends in a Cartesian Explosion❣️

Martin Bernaola Mendez
2 min readFeb 15, 2025

--

“Love is in the air, and so are LINQ queries! This Valentine’s Day, let’s talk about the passionate but sometimes dangerous relationship between SelectMany and Include. While they may seem like the perfect match, their love story can quickly turn into a Cartesian explosion if not handled carefully."

SelectMany: A Love Triangle

Is like a matchmaker, trying to pair every element from one collection with every element from another.

This code is like setting up blind dates between every user and every order, leading to an overwhelming number of combinations.

Consequences of a Cartesian explosion with SelectMany

  • Too many “dates” to handle, leading to performance issues.
  • Memory overload and slower execution.

How to avoid a Cartesian explosion with SelectMany

  1. Filter before combining: Use Where to ensure only compatible pairs are matched.

2. Use Join for a more stable relationship: Replace SelectMany with Join to create meaningful connections.

3. Limit the number of “dates”: Use Take or Skip to keep the number of combinations under control.

Include: When Love gets Too complicated..

Is like a romantic partner who wants to bring all their friends (related data) to the relationship.

This query is like inviting everyone to a Valentine’s Day dinner, amount of data.

Consequences of a Cartesian explosion with Include

  • Too many “guests” at the party, causing performance issues.
  • Memory overload and slower query execution

How to avoid a Cartesian explosion with Include

  1. Use projections (Select) for a more intimate gathering: Select only the necessary data.

2. Load related data explicitly: Only bring in the “friends” (related data) when absolutely necessary.

3. Split the party into smaller gatherings: Break down complex queries into smaller, more manageable parts.

4.Use ThenInclude sparingly: Avoid inviting too many levels of relationships to the party.

This Valentine’s Day, may your LINQ queries be as smooth as a romantic dinner for two, and may your databases never suffer the chaos of a Cartesian explosion. Happy love and query optimization day!

--

--

Martin Bernaola Mendez
Martin Bernaola Mendez

Written by Martin Bernaola Mendez

I am an Information Software Engineer. Welcome and enjoy the "Post Solutions" to make life easier

No responses yet