我有以下内容:
IDictionary<QuestionDuration, Int32> rules = _service.GetRules();
List<Question> questions = _service.GetQuestions();
public class Question {
public QuestionDuration Duration { get; set; }
}
字典值(Int32)是我需要从具有该特定持续时间的列表中获取的问题数...如果我有字典:
{{QuestionDuration.M2,5},{QuestionDuration.M4,3},{QuestionDuration.M8,0},...
所以我需要在原始列表中创建一个列表,包括5分钟2分钟,4分钟3分钟,0分钟8分钟等等...
我试图分组并使用lambda表达式,但我无法...
我该怎么做?
谢谢,
米格尔
答案 0 :(得分:5)
这将创建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();
提示:如果您需要在每个列表中选择随机问题,请在OrderBy(q => Guid.NewGuid())
运算符之前添加Take
。或者更随机的解决方案:
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();