C# 随机列表

一、问题描述

  在EF中使用随机排序出现的问题:LINQ to Entities does not recognize the method 'System.Guid NewId()' method, and this method cannot be translated into a store expression .

  解释就是:在使用 LINQ TO Entities 中生成的 sql 语句中找不到该 System.Guid NewId() 方法。毕竟在 sql 中确实不存在该函数。

二、解决思路 

  那就是从数据库中取出数据,拿到数据在进行排序,返回到客户端。

第一种使用 Random 随机排序:

var query = BuildQuery(_infoRepository
                .GetAll()
                .PageBy(input)
                .ToListAsync() 
Random random = new Random();
var ent = (from q in query  select new { q, r = random.Next(1, 10) });
var t = ent.OrderBy(x => x.r).Select(x => x.q).ToList();

第二种使用 Guid 随机排序:

var query = BuildQuery(_infoRepository
                .GetAll();
var querySetTop = query.ToList().OrderBy(x => Guid.NewGuid());

先使用 ToList() 方法表示已经把数据从数据库加载到客户端了,在进行排序就ok了。

原文地址:https://www.cnblogs.com/gzbit-zxx/p/10633730.html