Linq - Searching for objects that have a predetermined list

Asked

Viewed 221 times

3

I have an entity from Many-to-Many, many students for many subjects. And I need to get all students who possess all the subjects I desire.

For example, subjects: Mathematics, Portuguese and Physics. I need to take only students who have these three subjects. If he possesses another matter, but possesses these three, all right. If he possesses only one or two of the matters in question, disregard, does not serve.

My relationship table is as follows:

tbAlunosMaterias
AlunoId
MateriaId

Is it possible to get this information through English or lambda? Something like:

var alunosDasMaterias = alunos.Contains(x => ... );

Where: students = list of all students with their respective subjects (x) = where I give the list of subjects the student must have

1 answer

2


You need to have mapped the association between Students and Subjects in your context:

public DbSet<AlunoMateria> AlunosMaterias { get; set; }

The sentence would be so:

var idsDasMaterias = new int[] { 1, 2, 3 }; // Não sei quais são os Ids, então estou chutando Ids para as matérias
var alunosDasMaterias = contexto.AlunosMaterias
                                .Where(am => idsDasMaterias.Contains(am.MateriaId))
                                .Select(am => am.Aluno)
                                .ToList();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.