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