I'm using C# 3.5
and am currently using Linq
to get all users from a user table and put them in a list.
Now I would like to return a random user from that list. What's the best way to go about doing that?
I'm using C# 3.5
and am currently using Linq
to get all users from a user table and put them in a list.
Now I would like to return a random user from that list. What's the best way to go about doing that?
Use
ElementAt
:How about something like this?
Like this:
The
Random
class can be used to generate pseudo-random numbers. Use it to generate a random number within the range of valid indices into your array or list.If you want to see more examples, I created several random-oriented LINQ extensions and published it in the article Extending LINQ with Random Operations.
Why not create a generic helper and/or extension?!
Usage would be:
for Entity Framework or Linq 2 Sql, can use this extension method