linq select a random row
I have a table called Quotes in linq-to-sql that contains 2 columns: author and quote. How do you select both columns of a random ro开发者_如何学编程w?
Random rand = new Random();
int toSkip = rand.Next(0, context.Quotes.Count);
context.Quotes.Skip(toSkip).Take(1).First();
If you're doing Linq-to-Objects and don't need this to work on SQL, you can use ElementAt()
instead of the more verbose Skip(toSkip).Take(1).First()
:
var rndGen = new Random(); // do this only once in your app/class/IoC container
int random = rndGen.Next(0, context.Quotes.Count);
context.Quotes.ElementAt(random);
I did it something like this:
list.ElementAt(rand.Next(list.Count());
I stuck a bunch of random operations, including select and shuffle, as extension methods. This makes them available just like all the other collection extension methods.
You can see my code in the article Extending LINQ with Random Operations.
Here is one way to achieve what you want to do:
var quotes = from q in dataContext.Quotes select q;
int count = quotes.Count();
int index = new Random().Next(count);
var randomQuote = quotes.Skip(index).FirstOrDefault();
try it:
list.OrderBy(x => Guid.NewGuid()).Take(1).first();
1 First create a class with rend property
public class tbl_EmpJobDetailsEntity
{
public int JpId { get; set; }
public int rend
{
get
{
Random rnd = new Random();
return rnd.Next(1, 100);
}
}
}
2 Linq query
var rendomise = (from v in db.tbl_EmpJobDetails
select new tbl_EmpJobDetailsEntity
{
JpId=v.JpId
}).OrderBy(o=>o.rend);
精彩评论