Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select 5 random objects from a List, but once an object is selected exclude other objects with the same property value

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading