List.Contains fails on object comparison
Use Any()
method:
if (!lstClass1.Any(x => x.sText == "text1"))
lstClass1.Add(new Class1("text1"));
This code:
if (!lstClass1.Contains(new Class1("text1")))
lstClass1.Add(new Class1("text1"));
Could only work if you would provide the Equals()
and GetHashCode()
methods for your Class1
to enable making the comparisons between two objects of this class. To achieve this your class should implement the IEquatable
interface.
So your Class1 could look like this:
public class Class1 : IEquatable<Class1>
{
public Class1(string sText)
{
this.sText = sText;
}
public string sText = "";
public bool Equals(Class1 other)
{
if (other == null)
return false;
if (this.sText == other.sText)
return true;
else
return false;
}
public override int GetHashCode()
{
return this.sText.GetHashCode();
}
}
Contains will only work correctly if you implement IEquatable in your case.
You may use the following code instead:
public class Class1 //: IEquatable<Class1>
{
public string sText = "";
public Class1(string sText)
{
this.sText = sText;
}
//public bool Equals(Class1 other)
//{
// return this.sText == other.sText;
//}
}
static void Main(string[] args)
{
List<Class1> lstClass1 = new List<Class1>() { new Class1("text1") };
if (!lstClass1.Contains(new Class1("text1")))
lstClass1.Add(new Class1("text1"));
Console.WriteLine(lstClass1.Count);
Console.ReadKey();
}
Uncomment the commented lines and you will see the difference.