从数据库中获取随机和特定的项目

时间:2012-10-17 07:16:09

标签: asp.net-mvc linq

这应该是怎么回事。表中将显示总共六个值,其中三个必须是特定的,其他三个随机的,当然它们不匹配。意思是, 如果我创建两个单独的Currencies模型实例(这是有问题的),并从一个单独的三个特定的我需要的实例,并使用其他实例获得随机三,我将不得不排除这3个细节第二审。实施例。

//instance
DateTime today = DateTime.Now.Date;
var currencies = db.Currencies.Where(c => c.DateCreated.Equals(today));

//first get three separate
currency1 = currencies.Where(c => c.Sign.Equals("EUR"));
currency2 = currencies.Where(c => c.Sign.Equals("USD"));
currency3 = currencies.Where(c => c.Sign.Equals("AUD"));

//second get three randoms
var currencies = db.Currencies.Where(c => c.DateCreated.Equals(today)).OrderBy(d => db.GetNewID()).Take(3);

现在,应该有一种方法(我认为)在第二次使用.Except来改变货币,但我不确定如何对三种值进行例外处理。怎么做?

1 个答案:

答案 0 :(得分:2)

来源:Getting random records from a table using LINQ to SQL

var currencies = db.Currencies.Where(c => c.DateCreated.Equals(today))
                                          .OrderBy(q => db.GetNewId())
                                          .Take(6);

参考:
Is there a way to select random rows?
Select N Random Records with Linq
linq: order by random

希望这有帮助..