我有一个类“Class1”,它在.NET 2.0 中有一个字符串变量“sText”。我已经创建了该类“lstClass1”的对象列表。它在设置其字符串变量后存储该类的许多对象。
完整代码为:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!lstClass1.Contains(new Class1("text1")))
lstClass1.Add(new Class1("text1"));
}
public List<Class1> lstClass1 = new List<Class1>();
}
public class Class1
{
public Class1(string sText)
{
this.sText = sText;
}
public string sText = "";
}
现在,问题是我只想添加具有唯一文本值的字符串的类对象。例如,如果 lstClass1 已经有一个带有字符串变量值“text1”的对象,那么它不应该允许添加一个也有“text1”的对象。所以,我写了代码:
if (!lstClass1.Contains(new Class1("text1")))
lstClass1.Add(new Class1("text1"));
但它总是允许添加文本“text1”,即使列表中已经有一个带有“text1”字符串的对象。我的假设是,在第一个按钮单击事件“button1_Click”时,将添加该对象,因为列表为空,但在下一个按钮单击 List.Contains 函数将检查列表中是否已经存在带有字符串变量“text1”的对象和如果找到,则不会添加。但它总是允许添加带有文本“text1”的对象,即使它已经存在于列表中。
请注意:我没有采用简单的字符串列表或字符串列表,因为我想以简单的方式解释我的列表、类和对象的大问题。
最佳答案
使用 Any()
方法:
if (!lstClass1.Any(x => x.sText == "text1"))
lstClass1.Add(new Class1("text1"));
这段代码:
if (!lstClass1.Contains(new Class1("text1")))
lstClass1.Add(new Class1("text1"));
只有提供
Equals()
才能工作和 GetHashCode()
Class1
的方法以便在此类的两个对象之间进行比较。为了实现这一点,你的类(class)应该实现 IEquatable
界面。所以你的 Class1 可能看起来像这样:
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();
}
}
关于c# - List.Contains 对象比较失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21624920/