Method Permutations
| Edit this pagePermutations<T>(IEnumerable<T>)
Generates a sequence of lists that represent the permutations of the original sequence.
Declaration
public static IEnumerable<IList<T>> Permutations<T>(this IEnumerable<T> sequence)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<T> | sequence | The original sequence to permute |
Returns
| Type | Description |
|---|---|
| IEnumerable<IList<T>> | A sequence of lists representing permutations of the original sequence |
Type Parameters
| Name | Description |
|---|---|
| T | The type of the elements in the sequence |
Remarks
A permutation is a unique re-ordering of the elements of the sequence.
This method is implemented by using deferred execution. However, sequence will be
consumed in it's entirety immediately when first element of the returned sequence is consumed.
Each permutation is materialized into a new list. There are N! permutations of a sequence, where N is the
number of elements in sequence.
Note that the original sequence is considered one of the permutations and will be returned as one of the results.
Examples
The following code example demonstrates how to enumerate the permutations of a sequence using Permutations.
var sequence = Enumerable.Range(0, 4);
// Partition a sequence
var result = sequence.Permutations();
Console.WriteLine(
$"""
[
{string.Join(Environment.NewLine, result.Select(r => "\t[" + string.Join(", ", r) + "]"))}
]
""");
// This code produces the following output:
// [
// [0, 1, 2, 3]
// [0, 1, 3, 2]
// [0, 2, 1, 3]
// [0, 2, 3, 1]
// [0, 3, 1, 2]
// [0, 3, 2, 1]
// [1, 0, 2, 3]
// [1, 0, 3, 2]
// [1, 2, 0, 3]
// [1, 2, 3, 0]
// [1, 3, 0, 2]
// [1, 3, 2, 0]
// [2, 0, 1, 3]
// [2, 0, 3, 1]
// [2, 1, 0, 3]
// [2, 1, 3, 0]
// [2, 3, 0, 1]
// [2, 3, 1, 0]
// [3, 0, 1, 2]
// [3, 0, 2, 1]
// [3, 1, 0, 2]
// [3, 1, 2, 0]
// [3, 2, 0, 1]
// [3, 2, 1, 0]
// ]
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException |
|
| ArgumentException |
|