相关疑难解决方法(0)

从C#中的List <T>中选择N个随机元素

我需要一个快速算法从通用列表中选择5个随机元素.例如,我想从a获得5个随机元素List<string>.

c# random algorithm collections element

145
推荐指数
14
解决办法
11万
查看次数

Linq to Entities,随机顺序

如何以随机顺序返回匹配的实体?
要明确这是Entity Framework的东西和LINQ to Entities.

(航空代码)

IEnumerable<MyEntity> results = from en in context.MyEntity
                                where en.type == myTypeVar
                                orderby ?????
                                select en;
Run Code Online (Sandbox Code Playgroud)

谢谢

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

public Guid Random()
{
    return new Guid();
}
Run Code Online (Sandbox Code Playgroud)

并使用此查询:

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

但我得到了这个错误:

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

编辑(当前代码):

IEnumerable<MyEntity> results = (from en in context.MyEntity
                                 where …
Run Code Online (Sandbox Code Playgroud)

c# linq-to-entities entity-framework

36
推荐指数
3
解决办法
4万
查看次数