Home > front end >  How to select 5 random objects from a List, but once an object is selected exclude other objects wit
How to select 5 random objects from a List, but once an object is selected exclude other objects wit

Time:12-27

I'm creating a quiz application API on .NET 6 and have a list of questions, each connected to a picture. The questions are send in a random sequence. I use the following code to achieve that:

var finalQuestionsOneToFive = _context.Questions.Where(q => q.Test.Id == id)
    .ToList().OrderBy(x => random.Next()).Take(5).ToList();

The question class currently has the following properties:

public class Question
{
    public int Id { get; set; }
    public string Task { get; set; } = string.Empty;
    public string Picture { get; set; } = string.Empty;
}

With this code I successfully send 5 random questions for a test, the problem that I'm facing is that I have questions for which I use the same picture and I want to avoid that questions with the same pictures get picked. Is there a way to make the "random picker" skip the questions with the same picture string once a question with that picture string was picked?

CodePudding user response:

I'm not sure but try this: DistinctBy

_context.Questions.Where(q => q.Test.Id == id)
.OrderBy(x => random.Next()).DistinctBy(x =>x.Picture).ToList();
  • Related