I think the proper way is to tell your program what it means for two Turma
types to be equal.
public class ClassStudents
{
public string Name { get; set; }
public int Value { get; set; }
// Override the equality operation to check for text value only
public override bool Equals(object obj)
{
if (obj is ClassStudents other) // use pattern matching
{
return Name.Equals(other.Name);
}
return false;
}
}
Now you can use the list method .Contains()
for checking if item exists.
{
List<ClassStudents> classStudents = new List<ClassStudents>();
public Test()
{
// Add three values
classStudents.Add(new ClassStudents() { Name="ABC", Value=101 });
classStudents.Add(new ClassStudents() { Name="IJK", Value=111 });
classStudents.Add(new ClassStudents() { Name="XYZ", Value=101 });
// Check if exists before adding this value
ClassStudents x = new ClassStudents() { Name="ABC", Value=121 };
// `Contains()` calls the `Equals()` method of `classStudents`
if (!classStudents.Contains(x))
{
classStudents.Add(x);
}
}
}
This results in the cleanest code because it is obvious what the check if(!classStudents.Contains(x))
does. Also you are leveraging the power of the CLR by adding intelligence to your types. OOP is all about adding methods in your user classes to define actions. In this case, I am definition what equality means for this type and now the CLR can use this information where needed.