使用LINQ 2 SQL从数据库表中检索随机记录/行? [英] Retrive Random Record/Row from DataBase Table Using LINQ 2 SQL?
问题描述
我在Default.aspx页上有一个每日报价标签".我的要求是我希望从数据库表报价"中选择一个随机报价,并将文本分配给报价标签",我正在使用Linq 2 SQL ??
这是我的GetAll()Linq 2 Sql查询
I have a "Quote of the Day Label" on my Default.aspx Page My requirement is that I want a random quote to be selected from the database table "Quotes" and assign the text to the "Quotelabel", I am Using Linq 2 Sql??
here''s my GetAll() Linq 2 Sql query
public static List<Quotes> GetAll()
{
List<Quotes> list = new List<Quotes>();
var query = from c in new HsInternetDBDataContext().Quotes
orderby c.DateCreated ascending
select c;
foreach (DAL.Quote dr in query.ToList())
{
l.Add(new Quotes(dr));
}
return list;
}
如何修改上述查询并从数据库中获得一个随机记录/报价?
或使用此GetAll()方法并在客户端选择一个随机记录以分配给我的QuoteLabel?
谢谢
Chetan.
how do i modify the above query and get a single Random record/Quote from database??
or use this GetAll() method and select a single random record on the client side to assign to my QuoteLabel??
Thank you,
Chetan.
推荐答案
读取所有引号并删除除一个引号外的所有引号似乎是浪费的.我将使用Linq2Sql功能来检索单个项目,如下所示:
首先,我将使用Count()查询报价数量.然后,我将生成一个介于0和Count()-1(含)之间的随机整数R.最后,我将使用Link2Sql来获得第R个报价,例如:
Reading all quotes and dropping all but one seems wasteful. I would use Linq2Sql capabilities to retrieve a single item, like this:
First, I would query the number of quotes using Count(). Then, I would generate a random integer R between 0 and Count()-1, inclusive. Finally, I would use Link2Sql to get R-th quote, like this:
var quote = new HsInternetDBDataContext()
.Quotes
.OrderBy(q => q.DateCreated)
.Skip(R)
.Take(1)
.Single();
祝你好运!
Good luck!
http://www.dailycoding.com/Posts/random_sort_a_list_using_linq. aspx [ ^ ]解释了如何随机排序一个列表.完成后,您可以选择最高值.
http://www.dailycoding.com/Posts/random_sort_a_list_using_linq.aspx[^] explains how to random sort a list. Once you do that, you can select the top value.
谢谢大家,让它在我的解决方案中起作用:
Thanks guys, got it working here''s my solution:
public static Quotes GetRandomQuotes()
{
HsInternetDBDataContext db = new HsInternetDBDataContext();
var query = from c in db.Quotes select c;
int count = query.Count();
if (query.Count() > 0)
{
Random r = new Random();
return new Quotes(query.ToList()[r.Next(0, count)]);
}
else
{
return new Quotes();
}
}
这篇关于使用LINQ 2 SQL从数据库表中检索随机记录/行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!