[英]Take N Items from List on Condition
I have the following: 我有以下几点:
IDictionary<QuestionDuration, Int32> rules = _service.GetRules();
List<Question> questions = _service.GetQuestions();
public class Question {
public QuestionDuration Duration { get; set; }
}
The dictionary values (Int32) are the number of questions I need to take from the list with that specific duration ... So if I have the dictionary: 字典值(Int32)是我需要从列表中选择特定持续时间的问题数量...因此,如果我有字典:
{ { QuestionDuration.M2, 5 }, { QuestionDuration.M4, 3 }, { QuestionDuration.M8, 0 }, ... {{QuestionDuration.M2,5},{QuestionDuration.M4,3},{QuestionDuration.M8,0},...
So I need to create a List from the original list with 5 questions of 2 minutes, 4 questions of 3 minutes, 0 questions of 8 minutes, etc ... 所以我需要从原始列表中创建一个列表,其中包含2分钟的5个问题,3分钟的4个问题,8分钟的0个问题,等等...
I was trying to group and use a lambda expression for this but I wasn't able ... 我试图对此进行分组并使用lambda表达式,但是我无法...
How can I do this? 我怎样才能做到这一点?
Thank You, 谢谢,
Miguel 米格尔
That will create IEnumerable<List<Question>>
(three lists for your dictionary of rules): 这将创建
IEnumerable<List<Question>>
(规则字典的三个列表):
IDictionary<QuestionDuration, Int32> rules = _service.GetRules();
List<Question> questions = _service.GetQuestions();
var query = from r in rules
select questions.Where(q => q.Duration == r.Key)
.Take(r.Value).ToList();
Tip: if you need to pick random questions in each list, then add OrderBy(q => Guid.NewGuid())
just before Take
operator. 提示:如果需要在每个列表中随机选择问题,则在
Take
运算符之前添加OrderBy(q => Guid.NewGuid())
。 Or more random solution: 或更随机的解决方案:
var rand = new Random();
var query = from r in rules
select questions.Where(q => q.Duration == r.Key)
.OrderBy(q => rand.Next())
.Take(r.Value).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.