Method RandomSubset
| Edit this pageRandomSubset<T>(IEnumerable<T>, int)
Returns a sequence of a specified size of random elements from the original sequence.
Declaration
public static IEnumerable<T> RandomSubset<T>(this IEnumerable<T> source, int subsetSize)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<T> | source | The sequence from which to return random elements. |
| int | subsetSize | The size of the random subset to return. |
Returns
| Type | Description |
|---|---|
| IEnumerable<T> | A random sequence of elements in random order from the original sequence. |
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 get a random subset of a sequence using RandomSubset.
var sequence = Enumerable.Range(1, 10);
// get a random subset of the above sequence
var result = sequence.RandomSubset(4);
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
// One possible output of the above sequence:
// (each run will have different results)
// [3, 6, 7, 5]
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException |
|
| ArgumentOutOfRangeException |
|
RandomSubset<T>(IEnumerable<T>, int, Random)
Returns a sequence of a specified size of random elements from the original sequence.
Declaration
public static IEnumerable<T> RandomSubset<T>(this IEnumerable<T> source, int subsetSize, Random rand)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<T> | source | The sequence from which to return random elements. |
| int | subsetSize | The size of the random subset to return. |
| Random | rand | A random generator used as part of the selection algorithm. |
Returns
| Type | Description |
|---|---|
| IEnumerable<T> | A random sequence of elements in random order from the original sequence. |
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 get a random subset of a sequence using RandomSubset.
var sequence = Enumerable.Range(1, 10);
// get a random subset of the above sequence
var result = sequence.RandomSubset(4, new Random(Seed: 5));
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
// This code produces the following output:
// [7, 8, 2, 6]
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException |
|
| ArgumentOutOfRangeException |
|