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

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

C# Sharp LINQ : Exercise-23 with Solution

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

Sample Solution:-

C# Sharp Code:

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

class  LinqExercise23
{
public static void Main(string[] args)
{
char[] charset1 = { 'X', 'Y', 'Z' };
int[] numset1 = { 1, 2, 3, 4 };

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

var cartesianProduct = from letterList in charset1
from numberList in numset1
select new { letterList, numberList };

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

OR

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

class  LinqExercise23
{
public static void Main(string[] args)
{
var set1 = new string[] {"X", "Y", "Z"};
var set2 = new int[] {1, 2, 3};

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

var cartesianProduct=
set1.SelectMany(p=> set2.Select(q=> p+q+' '));

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

Sample Output:

```LINQ : Generate a Cartesian Product of two sets :
------------------------------------------------
The Cartesian Product are :
{ letterList = X, numberList = 1 }
{ letterList = X, numberList = 2 }
{ letterList = X, numberList = 3 }
{ letterList = X, numberList = 4 }
{ letterList = Y, numberList = 1 }
{ letterList = Y, numberList = 2 }
{ letterList = Y, numberList = 3 }
{ letterList = Y, numberList = 4 }
{ letterList = Z, numberList = 1 }
{ letterList = Z, numberList = 2 }
{ letterList = Z, numberList = 3 }
{ letterList = Z, numberList = 4 }
```

Flowchart:

C# Sharp Code Editor: