Find an object in a List where 2 equal objects do not have the same instance

0

I'm wanting to fill a comboBox with a series of Matters but I do not want it to be repeated. What I do is go through courses already filtered for the student that contain a subject id.

listaCursos = curlog.GetAllFiltrados();
        foreach (Curso c in listaCursos)
        {
            Materia = matlog.GetOne(c.IDMateria);
            if (idPlan == Materia.IdPlan)
            {
                if (!materiasFiltradas.Contains(Materia))//ACA ESTA EL PROBLEMA
                {
                    materiasFiltradas.Add(Materia);
                } 
            }
        }

I bring the Matter, I notice if they are of the student's plan and I add it to a list. The problem appears when I want to see if the matter is already in the list, because the Contains method works with the reference to the instance of the object and not the content, so even if the matter is the same, it does not take it as the same. How can I do so that I do not add the same subject twice? Thanks!

    
asked by nico_31 12.10.2018 в 15:05
source

1 answer

2

If you use Linq you can perform a search using Any() , the function what it does is find the elements that meet a certain condition and if there is at least 1 element it will return a true but false with the what your conditionals can work on.

That would be what you want:

    listaCursos = curlog.GetAllFiltrados();
    foreach (Curso c in listaCursos)
    {
        Materia = matlog.GetOne(c.IDMateria);
        if (idPlan == Materia.IdPlan)
        {
            if(!materiasFiltradas.Any(x => x.IDMateria == Materia.IDMateria))
            {
                materiasFiltradas.Add(Materia);
            } 
        }
    }
    
answered by 12.10.2018 / 15:19
source