Home > Database > Mysql Tutorial > How Can LINQ Perform a Cartesian Product with a Variable Number of Sets?

How Can LINQ Perform a Cartesian Product with a Variable Number of Sets?

Patricia Arquette
Release: 2025-01-17 07:07:12
Original
520 people have browsed it

How Can LINQ Perform a Cartesian Product with a Variable Number of Sets?

Implementing Cartesian product with variable number of sets using LINQ

Suppose a class structure contains a person, multiple dogs, and multiple puppies for each dog. The goal is to generate a list of all possible puppy combinations, selecting one puppy from each dog.

In SQL, this can be achieved using the Cartesian product operation, for example:

<code class="language-sql">select * from puppies a, puppies b where a.parent='dog1' and b.parent='dog2'</code>
Copy after login

Is it possible to perform similar operations using LINQ?

If the set size of dogs (i.e. the number of dogs) is known at compile time, a straightforward approach can be used:

<code class="language-csharp">from p1 in dog1.Puppies
from p2 in dog2.Puppies
from p3 in dog3.Puppies
select new {p1, p2, p3};</code>
Copy after login

However, if the collection number of dogs is unknown, a more general approach is needed. Eric Lippert details a solution in his article and on StackOverflow that involves creating a custom method to calculate the Cartesian product:

<code class="language-csharp">public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(IEnumerable<IEnumerable<T>> sets) {
    // ... implementation omitted for brevity
}</code>
Copy after login

Using this method, the desired query can be expressed as:

<code class="language-csharp">CartesianProduct(from dog in person.Dogs select dog.Puppies)</code>
Copy after login

This will return a sequence of puppy sequences, where each sequence represents a combination of one puppy from each dog. For example, if dogs 'dog1' and 'dog2' have puppies 'p11', 'p12' and 'p21' respectively, the output will be:

<code>{p11, p21}
{p11, p22}
{p12, p21}
{p12, p22}</code>
Copy after login

The above is the detailed content of How Can LINQ Perform a Cartesian Product with a Variable Number of Sets?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template