简体   繁体   English

多随机选择 Linq

[英]Multiple randomly selection Linq

I have Questions table and List of CategoryIds .我有Questions表和CategoryIds列表。 I have to get one question from each CategoryId randomly.我必须从每个CategoryId随机得到一个问题。 Right now I'm doing like this:现在我正在这样做:

var randomQuestions = new List<Question>();
foreach(int id in categoryIds){

randomQuestions.add(questions.Where(o => o.CategoryId== id).OrderBy(o => Guid.NewGuid()).FirstOrDefault());
}

But is there way to do it only with Linq?但是有没有办法只用 Linq 做到这一点? Thanks谢谢

This should do what you want in one query这应该在一个查询中完成您想要的

var randomQuestions = questions
    .Where(q => categoryIds.Contains(q.CategoryId))
    .GroupBy(q = > q.CategoryId)
    .Select(grp => grp.OrderBy(_ => Guid.NewGuid()).First())
    .ToList();

That will first filter only questions in the categories you care about, then it groups on the category id and for each group it randomly picks one.这将首先仅过滤您关心的类别中的问题,然后根据类别 id 进行分组,并为每个组随机选择一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM