自定义对象的检查列表

Checking list for custom object

如果您已经创建了一个自定义对象列表,如果您想在添加之前检查该列表以查看它是否包含一个对象,那么它是否必须与哈希码有关,我的意思是这样您就不会得到重复项在列表中或者是否有更简单的方法基本上我想在自定义对象列表上使用 contains 方法来查看我要添加的对象是否已经存在于列表中,如果有更简单的方法则必须处理哈希码?

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataConverter.Objects;

namespace DataConverter.Converters
{
    class CategoryConverter
    {
        private Category category;
        private SubCategory subCategory;
        private ExcellObj excellObj; 
         


        public CategoryConverter(string path)
        {
            excellObj = new ExcellObj(path); 
        }

        public List<Category> getCategoryListExcel()
        {
            List<Category> categories = new List<Category>();

            List<string> ColumnNames = new List<string> { "Group1", "Group1Descr" };
            List<int> CorrectColumn = new List<int>(); 


            for(int i = 0; i < ColumnNames.Count; i++)
            {
                CorrectColumn.Add(excellObj.findColumn(ColumnNames[i]));
            }

            
            for(int i = 2; i < excellObj.allRows; i++)
            {   
              
                   
                
                    categories.Add(category = new Category(excellObj.getValuesFromCell(i, CorrectColumn[1]), excellObj.getValuesFromCell(i, CorrectColumn[0]), "Home"));
                
              
            }


            





            return categories; 


        }
        public List<List<SubCategory>> getSubCategory()
        {
            List<SubCategory> subCategories1 = new List<SubCategory>();
            List<SubCategory> subCategories2 = new List<SubCategory>();
            List<List<SubCategory>> subCategoriesList = new List<List<SubCategory>>(); 
            List<string> ColumnNamesSubCategory1 = new List<string> { "Group2", "Group2Descr" };
            List<string> ColumnNamesSubCategory2 = new List<string> { "Group3", "Group3Desc" };
            List<int> CorrectColumn1 = new List<int>();
            List<int> CorrectColumn2 = new List<int>();


            for(int i = 0; i < ColumnNamesSubCategory1.Count; i++)
            {
                CorrectColumn1.Add(excellObj.findColumn(ColumnNamesSubCategory1[i]));
                CorrectColumn2.Add(excellObj.findColumn(ColumnNamesSubCategory2[i]));
            }

            for(int i = 1; i < excellObj.allRows; i++)
            {
                subCategories1.Add(subCategory = new SubCategory(excellObj.getValuesFromCell(i, CorrectColumn1[1]),excellObj.getValuesFromCell(i,CorrectColumn1[0]), "Home"));
                subCategories2.Add(subCategory = new SubCategory(excellObj.getValuesFromCell(i,CorrectColumn2[1]), excellObj.getValuesFromCell(i,CorrectColumn2[0]), "Home"));
            }

            subCategoriesList.Add(subCategories1);
            subCategoriesList.Add(subCategories2);


            return subCategoriesList;
        }

        public void finnishedUsingExcel()
        {
            excellObj.CloseApplication();
        }

    }
}

而我想要发生的是我想要 运行 a

if(categories.Contains(category) == false){
    categories.add(category)
}

我不明白文档中的这一部分?

   public Person(string lastName, string ssn)
   {
      if (Regex.IsMatch(ssn, @"\d{9}"))
        uniqueSsn = $"{ssn.Substring(0, 3)}-{ssn.Substring(3, 2)}-{ssn.Substring(5, 4)}";
      else if (Regex.IsMatch(ssn, @"\d{3}-\d{2}-\d{4}"))
         uniqueSsn = ssn;
      else
         throw new FormatException("The social security number has an invalid format.");

      this.LastName = lastName;
   }

假设您有这样的代码:

List<CustomObject> listOfCustomObjects = new List<CustomObject>();

解决方案 1

如果是这样,您可以使用 listOfCustomObjects.Contains(customObject) 找出 customObject 是否在 listOfCustomObjects 中。您应该将 using System.Linq; 添加到代码的顶部才能使用此方法。

解决方案 2

另一种在列表中不重复的方法基本上是不使用 List。您可以改用 HashSet。使用此方法,不会将重复的对象自动添加到您的列表中。 HashSet 也在 LINQ 库中,因此您也应该为此解决方案添加行 using System.Linq;。这是一个如何使用 CustomObject class:

创建新 HashSet 的示例
HashSet<CustomObject> setOfCustomObjects = new HashSet<CustomObject>();

如果合理的话,您确实应该让 class 实现 IEquatable,并且您将以任何频率检查是否相等,只是这样它就不会咬到您。 "Contains" 方法将起作用,但仅用于测试是否存在 exact 相同的实例,不一定是仅共享匹配属性的实例。考虑以下代码:

class Program
    {
        static void Main(string[] args)
        {
            var classInstance = new MySampleClass("testA", "testB");

            var classList = new List<MySampleClass>();
            classList.Add(classInstance);

            if (classList.Contains(new MySampleClass("testA", "testB")))
            {
                Console.WriteLine("true");
            }
            else
            {
                Console.WriteLine("false");
            }

            if (classList.Contains(classInstance))
            {
                Console.WriteLine("true");
            }
            else
            {
                Console.WriteLine("false");
            }
        }
    }

    public class MySampleClass
    {
        public string SampleProperty1 { get; set; }
        public string SampleProperty2 { get; set; }

        public MySampleClass(string sampleProperty1, string sampleProperty2)
        {
            SampleProperty1 = sampleProperty1;
            SampleProperty2 = sampleProperty2;
        }
    }

即使我们正在检查是否存在与我们之前添加的值完全相同的 class,它们仍然是单独的实例,您最终会在您的列表。

在非常有限的情况下,另一种方法是使用 LINQ 方法检查列表是否已经包含具有 属性 且 可以 进行比较的条目,例如 int ID 或其他东西:

 yourList.Any(item => item.Id.Equals(otherItem.Id));

再次重申,如果不止一次,请使用 IEquatable 以正确的方式实现它。参见 Microsoft's documentation