﻿ C# Sharp Exercises: LINQ : Generate a Cartesian Product of three sets - w3resource

# C# Sharp Exercises: LINQ : Generate a Cartesian Product of three sets

## C# Sharp LINQ : Exercise-24 with Solution

Write a program in C# Sharp to generate a Cartesian Product of three sets.

Sample Solution:-

C# Sharp Code:

``````using System;
using System.Linq;
using System.Collections.Generic;

class  LinqExercise24
{
public static void Main(string[] args)
{
char[] charset1 = { 'X', 'Y', 'Z' };
int[] numset1 = { 1, 2, 3 };
string[] colorset1 = { "Green", "Orange" };

Console.Write("\nLINQ : Generate a Cartesian Product of three sets : ");
Console.Write("\n----------------------------------------------------\n");

var cartesianProduct = from letter in charset1
from number in numset1
from colour in colorset1
select new { letter, number, colour };

Console.Write("The Cartesian Product are : \n");
foreach (var ProductList in cartesianProduct)
{
Console.WriteLine(ProductList);
}
}
}
```
```

OR

``````using System;
using System.Linq;
using System.Collections.Generic;

class  LinqExercise24
{
public static void Main(string[] args)
{

char[] set1 = { 'X', 'Y', 'Z' };
int[] set2 = { 1, 2, 3 };
string[] set3 = { "Green", "Pink" };

Console.Write("\nLINQ : Generate a Cartesian Product of three sets: ");
Console.Write("\n---------------------------------------------------\n");

var set12CartesianProduct = set1.SelectMany(
letterList => set2.Select(numList =>
new { letterList, numList }));

var cartesianProduct = set12CartesianProduct.SelectMany(
(set1and2) => set3.Select(colorList =>
new { set1and2.letterList, set1and2.numList, colorList }));

Console.Write("The Cartesian Product are : \n");
foreach (var ProductList in cartesianProduct)
{
Console.WriteLine(ProductList);
}
}
}
```
```

Sample Output:

```LINQ : Generate a Cartesian Product of three sets :
----------------------------------------------------
The Cartesian Product are :
{ letter = X, number = 1, colour = Green }
{ letter = X, number = 1, colour = Orange }
{ letter = X, number = 2, colour = Green }
{ letter = X, number = 2, colour = Orange }
{ letter = X, number = 3, colour = Green }
{ letter = X, number = 3, colour = Orange }
{ letter = Y, number = 1, colour = Green }
{ letter = Y, number = 1, colour = Orange }
{ letter = Y, number = 2, colour = Green }
{ letter = Y, number = 2, colour = Orange }
{ letter = Y, number = 3, colour = Green }
{ letter = Y, number = 3, colour = Orange }
{ letter = Z, number = 1, colour = Green }
{ letter = Z, number = 1, colour = Orange }
{ letter = Z, number = 2, colour = Green }
{ letter = Z, number = 2, colour = Orange }
{ letter = Z, number = 3, colour = Green }
{ letter = Z, number = 3, colour = Orange }
```

Flowchart:

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

﻿

New Content: Composer: Dependency manager for PHP, R Programming