Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

248
Vistas
How to check if a list contains specific class in C#

Several classes inherit from abstract class Illness and overrides a field name
Illness.cs:

namespace health;
abstract class Illness{
    public abstract string name { get;}
}

class Cancer : Illness{
    public override string name { 
        get{ return "Cancer";}
    }
}

class Covid : Illness{
    public override string name { 
        get{ return "Covid";}
    }
}

There is an empty list List<Illness> illnesses = new List<Illness> in main class and the goal is to make a method, which adds a value to illnesses list only if this list doesn't contain the given class already.
Tried to do this:

public void addIllness(Illness illness){
        if (!illnesses.Contains(illness)){
            illnesses.Add(illness);
        }
    }

but not working.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can (as mentioned by Lei Yang) solve this by checking he type:

  • if(!illnesses.Any(i=>i is typeof(Covid)){ ... } for a specific type.
  • if (!illnesses.Any(i => i.GetType() == illness.GetType())) { ... } comparing the type of the objects.

You could also create a generic method to achieve this in a nice manner:

public void Add<T>(T illness) where T : Illness{
    if(!illnesses.Any(t=>t is T)){
        illnesses.Add(illness);
    }
}

As you are overriding name you could even use that for better performance:

if(!illnesses.Any(i=>i.name == illness.name)){ ... } This is however more or less the explicit version of what (again) @Lei Yang proposed in implementing IEquatable.

This however seems to be a bit strange of an approach, you should use objects when you can have more than one instance of a class, else maybe reconsider adding a "IllnessType" enum beside the Name and ditch the inheritance.

over 4 years ago · Santiago Trujillo Denunciar

0

You can check class using GetType method.

if (!illnesses.Any(i => i.GetType() == illness.GetType()))
{
   illnesses.Add(illness);
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda