c# - List.Contains 对象比较失败

标签 c# .net list class object

我有一个类“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"));

仅当您为 Class1 提供 Equals()GetHashCode() 方法时才能工作,以便能够在两者之间进行比较这个类的对象。为此,您的类应实现 IEquatable 接口(interface)。 所以你的 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/

相关文章:

c# - List<int> 需要很长时间才能使用 Nhibernate Criteria 进行实例化

c# - 为什么 C# 中的数字格式字符串在不使用小数 (F0) 时将数字四舍五入?

c# - 如何在 C# 中执行每次迭代延迟 1 分钟的无限循环?

c# - 如何将自定义属性添加到 DynamicMethod 生成的方法?

c# - 为什么我的 C# 默认接口(interface)实现在具体类定义中没有被识别?

java - 创建排除引号内容的空格分隔列表

java - 使用泛型和参数化列表的问题

c# - 使用 log4net 在运行时读取并记录 HttpSession 数据

c# - 为什么添加参数化构造函数时默认构造函数不起作用?

c# - 如何从基于复选框的 View 传递对象?