Reputation: 39364
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:
{ { 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 ...
I was trying to group and use a lambda expression for this but I wasn't able ...
How can I do this?
Thank You,
Miguel
Upvotes: 2
Views: 341
Reputation: 236208
That will create IEnumerable<List<Question>>
(three lists for your dictionary of rules):
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. 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();
Upvotes: 5