S
shapper
Hello,
How can I get a random record using linq?
Thanks,
Miguel
How can I get a random record using linq?
Thanks,
Miguel
See Count(), Skip(), and Take().
Take your pick. Do you want to use LINQ or don't you?![]()
Take the first 'row(s)' after a random sort (which implies you can
implement a sort delegate function wich randomly returns -1, 0, or 1, as
example, for IComparer<T>).
"But that implication is false."
You tried it?
"But that implication is false."
You tried it?
the first N elements.
Your example is not relevant to the discussion.
returns -1 said:By the way, I don't meant to
return "a number" between -1 and +1, but one of the three numbers, -1, 0 and
1
randomly, 'ad hoc', as 'asked' and the observation is based on the fact
that the algorithm would ask JUST ONCE, for two given 'objects', A and B,
if A<B, if A=B or if A>B. So, ANSWERING to that QUESTION randomly once for
all before the process starts, or 'ad hoc', AS I PROPOSED, is logically
equivalent.
And I failed to answer specifically to your objection about
- if A > B (by previous comparison between A and B)
- and if B > C (again by a previous comparison)
Your objection was that then, nothing would insure us that a randombly
generated answer betwenn A and C would return A > C . While your
objection is right about the nothingness (while is it also possible to
store the generated random value, once it is generated), it is somehow
irrelevant since the algorithm won't need to compare A with C in the
first place, since it already knows the relative position of C to B to
A... unless you use a very innefficient sorting algorithm.
You probably meant the quick sort is O(n2) in the worst case, and a
Merge sort O(n log n)
but you are right about using a shuffling algorithm would be more
effective than sorting on a random value to start with, assuming
'position' for the elements are available (as example, they are not
exposed for rows in a database table).
I recognize that I was wrong about the possibility to use a memoryless
sort with the sorting algorithm used by the Framework.
shapper said:See Count(), Skip(), and Take().
What about using an extension?
private static Random random = new Random();
public static T GetRandom<T>(this IList<T> list) {
if (list.Count == 0) {
return default(T);
}
return list[random.Next(0, list.Count)];
}
But would it possible, or even make sense, to make this extension work
with List, IEnumerable, etc?
Thanks,
Miguel