Method Shuffle
| Edit this pageShuffle<T>(IEnumerable<T>)
Returns a sequence of elements in random order from the original sequence.
Declaration
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<T> | source | The sequence from which to return random elements. |
Returns
| Type | Description |
|---|---|
| IEnumerable<T> | A sequence of elements |
Type Parameters
| Name | Description |
|---|---|
| T | The type of source sequence elements. |
Remarks
This method is implemented by using deferred execution. However, source will be consumed
in it's entirety immediately when first element of the returned sequence is consumed.
Examples
The following code example demonstrates how to shuffle a sequence using Shuffle.
var sequence = Enumerable.Range(1, 10);
// Shuffle a sequence
var result = sequence.Shuffle();
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
// One possible random output is as follows:
// [10, 9, 3, 8, 1, 6, 2, 4, 7, 5]
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException |
|
Shuffle<T>(IEnumerable<T>, Random)
Returns a sequence of elements in random order from the original sequence. An additional parameter specifies a random generator to be used for the random selection algorithm.
Declaration
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rand)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<T> | source | The sequence from which to return random elements. |
| Random | rand | A random generator used as part of the selection algorithm. |
Returns
| Type | Description |
|---|---|
| IEnumerable<T> | A sequence of elements |
Type Parameters
| Name | Description |
|---|---|
| T | The type of source sequence elements. |
Remarks
This method is implemented by using deferred execution. However, source will be consumed
in it's entirety immediately when first element of the returned sequence is consumed.
Examples
The following code example demonstrates how to shuffle a sequence using Shuffle.
var sequence = Enumerable.Range(1, 10);
// Shuffle a sequence
var result = sequence.Shuffle(new Random(10));
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
// This code produces the following output:
// [1, 4, 2, 6, 3, 9, 5, 7, 10, 8]
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException |
|