简体   繁体   English

LINQ2SQL获取随机记录

[英]LINQ2SQL Get random record

I found this handy query; 我找到了这个方便的查询;

SELECT TOP 1 * FROM Advertising ORDER BY NEWID()

but need to turn it into a LINQ query. 但需要将其转换为LINQ查询。

I tried doing something like; 我尝试过这样的事情;

var a = (from record in Advertising
        select record)

but can't figure out how to do the ordering so that a random record is returned. 但无法弄清楚如何进行排序以便返回随机记录。

It is probably easiest to just execute the command directly. 直接执行命令可能最简单。

var a = ctx.ExecuteQuery<Advertising>("select top 1 * from Advertising order by NEWID()").First();

You could also do it with an sproc, or if you want a totally generic way to do it you can query the count, then generate a random number in that range and skip. 您也可以使用sproc执行此操作,或者如果您需要完全通用的方法来执行此操作,则可以查询计数,然后在该范围内生成随机数并跳过。 (As others have noted while I was typing this) (正如其他人在我输入时所说的那样)

This won't generate the SQL you're looking at, but should return a random result without having to retrieve all records: 这不会生成您正在查看的SQL,但应该返回随机结果而不必检索所有记录:

Random r = new Random();
var record = r.Next(Advertising.Count());

var randomRecord = Advertising.Skip(record).FirstOrDefault(1);

Edit: It should also be more efficient than a random sort (unless SQL Server optimizes the sort away) 编辑:它应该比随机排序更有效(除非SQL Server优化排序)

Edit 2: Take(1) should be FirstOrDefault() to return a record, instead of a list 1 record long. 编辑2:Take(1)应该是FirstOrDefault()返回记录,而不是列表1记录长。

here is my get random method 这是我的随机方法

Public Shared Function GetSingleRandom(Of T)(ByVal target As IEnumerable(Of T)) As T
        Dim r As New Random(DateTime.Now.Millisecond)
        Dim position As Integer = r.Next(target.Count)
        Return target.ElementAt(position)
    End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM