C
C#3mo ago
ArpeggioAndy

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
Angius3mo ago
It orders the elements by random number
ArpeggioAndy
ArpeggioAndyOP3mo ago
What is that supposed to mean
MODiX
MODiX3mo 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
Angius3mo 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
ArpeggioAndyOP3mo ago
Hmm, interesting. How would you go about it?
Pobiega
Pobiega3mo ago
if its an array, you can index a given location directly so jsut randomize an index
Angius
Angius3mo ago
^
arr[Random.Shared.Next(0, arr.Length)]
arr[Random.Shared.Next(0, arr.Length)]
Pobiega
Pobiega3mo 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
Sehra3mo ago
-1? upper bound is exclusive
Angius
Angius3mo ago
Ah, derp, you're right
Sehra
Sehra3mo ago
if you need multiple random items, there is also Random.GetItems with various overloads
ArpeggioAndy
ArpeggioAndyOP3mo ago
Why this instead of like arr[Random.Range(0, arr.Length)]?
Angius
Angius3mo ago
No description
Angius
Angius3mo 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
ArpeggioAndyOP3mo ago
Oh yeah it is maybe that's where its coming from

Did you find this page helpful?