Enumerable.OrderBy help

I'm following a tutorial and they randomly get an element of an enumerable like this:
return unvisitedCells.OrderBy(_ => Random.Range(0, 10)).FirstOrDefault();
return unvisitedCells.OrderBy(_ => Random.Range(0, 10)).FirstOrDefault();
I'm a bit confused as to how this works. I looked up the docs for .OrderBy and kind of understand how it's usually meant to be used, but I don't see what throwing a random number in there does exactly.
15 Replies
Angius
Angius5w ago
It orders the elements by random number
ArpeggioAndy
ArpeggioAndyOP5w ago
What is that supposed to mean
MODiX
MODiX5w ago
Angius
REPL Result: Success
int[] arr = { 1, 27, 57, 67, 16, 44, 5 };
arr.Select(num => (num, Random.Shared.Next(0, 10)))
int[] arr = { 1, 27, 57, 67, 16, 44, 5 };
arr.Select(num => (num, Random.Shared.Next(0, 10)))
Result: List<ValueTuple<int, int>>
[
{
"item1": 1,
"item2": 6
},
{
"item1": 27,
"item2": 7
},
{
"item1": 57,
"item2": 6
},
{
"item1": 67,
"item2": 9
},
{
"item1": 16,
"item2": 4
},
{
"item1": 44,
"item2": 2
},
{
"item1": 5,
"item2": 3
}
]
[
{
"item1": 1,
"item2": 6
},
{
"item1": 27,
"item2": 7
},
{
"item1": 57,
"item2": 6
},
{
"item1": 67,
"item2": 9
},
{
"item1": 16,
"item2": 4
},
{
"item1": 44,
"item2": 2
},
{
"item1": 5,
"item2": 3
}
]
Compile: 373.080ms | Execution: 114.542ms | React with ❌ to remove this embed.
Angius
Angius5w ago
It does something like this under the hood For each element, it generates a random number, and orders by that random number Not how I would do getting a random item from an array, but it works
ArpeggioAndy
ArpeggioAndyOP5w ago
Hmm, interesting. How would you go about it?
Pobiega
Pobiega5w ago
if its an array, you can index a given location directly so jsut randomize an index
Angius
Angius5w ago
^
arr[Random.Shared.Next(0, arr.Length)]
arr[Random.Shared.Next(0, arr.Length)]
Pobiega
Pobiega5w ago
OrderBy implies going through the entire sequence, generating a random number for each item, then sorting the list wayyy more work for the computer
Sehra
Sehra5w ago
-1? upper bound is exclusive
Angius
Angius5w ago
Ah, derp, you're right
Sehra
Sehra5w ago
if you need multiple random items, there is also Random.GetItems with various overloads
ArpeggioAndy
ArpeggioAndyOP5w ago
Why this instead of like arr[Random.Range(0, arr.Length)]?
Angius
Angius5w ago
No description
Angius
Angius5w ago
Random class does not have a static Range method https://learn.microsoft.com/en-us/dotnet/api/System.Random?view=net-9.0#methods Is this a Unity thing or something?
ArpeggioAndy
ArpeggioAndyOP5w ago
Oh yeah it is maybe that's where its coming from

Did you find this page helpful?