小编典典

Linq to Entities,随机顺序

c#

如何以随机顺序返回匹配的实体?
为了清楚起见,这是实体框架的东西和LINQ to Entities。

(航空代码)

IEnumerable<MyEntity> results = from en in context.MyEntity
                                where en.type == myTypeVar
                                orderby ?????
                                select en;

谢谢

编辑:
我尝试将其添加到上下文中:

public Guid Random()
{
    return new Guid();
}

并使用以下查询:

IEnumerable<MyEntity> results = from en in context.MyEntity
                                where en.type == myTypeVar
                                orderby context.Random()
                                select en;

但是我得到了这个错误:

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Guid Random()' method, and this method cannot be translated into a store expression..

编辑(当前代码):

IEnumerable<MyEntity> results = (from en in context.MyEntity
                                 where en.type == myTypeVar
                                 orderby context.Random()
                                 select en).AsEnumerable();

阅读 192

收藏
2020-05-19

共1个答案

小编典典

简单的解决方案是创建一个数组(或一个List<T>),然后随机化其索引。

编辑:

static IEnumerable<T> Randomize<T>(this IEnumerable<T> source) {
  var array = source.ToArray();
  // randomize indexes (several approaches are possible)
  return array;
}

编辑:就个人而言,我发现乔恩·斯基特的答案更为优雅:

var results = from ... in ... where ... orderby Guid.NewGuid() select ...

当然,您可以使用随机数生成器代替Guid.NewGuid()

2020-05-19