I've a method which returns a generic list collection(List) from the database. This collection has got order details i.e., Order Id, order name, product details etc.
Also, method the method returns a collection having only the top 5 orders sorted by order date descending.
My requirement is that each time the client calls this method, I need to return collection which has got 5 random orders.
How do I achieve this using C#?
I wrote a TakeRandom extension method a while back which does this using a Fisher-Yates shuffle. It's pretty efficient as it only bothers to randomise the number of items that you actually want to return, and is guaranteed to be unbiased.
An implementation of ThreadSafeRandom can be found at the PFX team blog.
You really should do this in the database - no point in returning a big stack of stuff only to drop all but five on the floor. You should amend your question to explain what typew of data access stack is involved so people can give better answers. For instance, you could do an ORDER BY RAND():
But that visits every row, which you don't want. If you're using SQL Server [and would like to be tied to it :P], you could use TABLESAMPLE.
If you're using LINQ to SQL, go here
EDIT: Just pretend the rest of this isnt here - it's not efficient and hence Greg's answer is far more desirable if you do want to sort client-side.
But, for completeness, paste the following into LINQPad:
EDIT: Brute force answer to Greg's point (Yes, not efficient or pretty)