Linq to Entity,随机顺序 [英] Linq to Entities, random order
本文介绍了Linq to Entity,随机顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以随机顺序返回匹配的实体?
只是要清楚这是实体框架的东西和 LINQ to Entities.
How do i return matching entities in a random order?
Just to be clear this is Entity Framework stuff and LINQ to Entities.
(航空代码)
IEnumerable<MyEntity> results = from en in context.MyEntity
where en.type == myTypeVar
orderby ?????
select en;
谢谢
我尝试将其添加到上下文中:
I tried adding this to the context:
public Guid Random()
{
return new Guid();
}
并使用此查询:
IEnumerable<MyEntity> results = from en in context.MyEntity
where en.type == myTypeVar
orderby context.Random()
select en;
但是我遇到了这个错误:
But i got this error:
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();
推荐答案
简单的解决方案是创建一个数组(或一个 List
),然后随机化其索引.
The simple solution would be creating an array (or a List<T>
) and than randomize its indexes.
static IEnumerable<T> Randomize<T>(this IEnumerable<T> source) {
var array = source.ToArray();
// randomize indexes (several approaches are possible)
return array;
}
就个人而言,我发现 Jon Skeet 的回答更优雅:
Personally, I find the answer of Jon Skeet is more elegant:
var results = from ... in ... where ... orderby Guid.NewGuid() select ...
当然,您可以使用随机数生成器代替 Guid.NewGuid()
.
And sure, you can take a random number generator instead of Guid.NewGuid()
.
这篇关于Linq to Entity,随机顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文