Method Transpose
| Edit this pageTranspose<T>(IEnumerable<IEnumerable<T>>)
Transposes a sequence of rows into a sequence of columns.
Declaration
public static IEnumerable<IEnumerable<T>> Transpose<T>(this IEnumerable<IEnumerable<T>> source)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<IEnumerable<T>> | source | Source sequence to transpose. |
Returns
| Type | Description |
|---|---|
| IEnumerable<IEnumerable<T>> | Returns a sequence of columns in the source swapped into rows. |
Type Parameters
| Name | Description |
|---|---|
| T | Type of source sequence elements. |
Remarks
If a rows is shorter than a follow it then the shorter row's elements are skipped in the corresponding column sequences. This operator uses deferred execution and streams its results. Source sequence is consumed greedily when an iteration begins. The inner sequences representing rows are consumed lazily and resulting sequences of columns are streamed.
Examples
The following code example demonstrates how to transpose a jagged 2d sequence using Transpose.
var matrix = new[]
{
new[] { 10, 11 },
new[] { 20 },
new[] { 30, 31, 32 }
};
// Transpose a 2d sequence
var result = matrix.Transpose();
Console.WriteLine(
"[" + Environment.NewLine +
string.Join(
", " + Environment.NewLine,
result.Select(c => " [" + string.Join(", ", c) + "]")) +
Environment.NewLine + "]");
// This code produces the following output:
// [
// [10, 20, 30],
// [11, 31],
// [32]
// ]
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException |
|