简体   繁体   中英

Checking list for custom object

If you have made a list of Custom objects is it a must to have to do with Hashcodes if you wanna check that list to see if it contains a object before adding it, I mean so that you do not get duplicates in the list or is there an easier way basically I want to use the contains method on a custom object list to see if the object I want to add already exists in the list and if there then is an easier way then to have to deal with hashcodes?

This is my code:

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();
        }

    }
}

and what i whant to happen is that i whant to run a

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

i do not understand this part in the documentation?

   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;
   }

Assuming you have a code like this:

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

Solution 1

If so, you can use listOfCustomObjects.Contains(customObject) to find out if customObject is in listOfCustomObjects . You should add using System.Linq; to the top of your code in order to use this method.

Solution 2

Another way to not have duplicates in your list is basically not using a List . You can use HashSet instead. With this method, duplicate objects won't be added to your list automatically. HashSet is also in LINQ Library, so you should add the line using System.Linq; for this solution too. Here's an example how to create a new HashSet with your CustomObject class:

HashSet<CustomObject> setOfCustomObjects = new HashSet<CustomObject>();

You really should have your class implement IEquatable if it's reasonable to do so and you're going to check for equality with any frequency, just so it does not bite you. The "Contains" method will work, but only to test that the exact same instance is present, not necessarily one that just shares matching properties. Consider the following code:

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;
        }
    }

Even though we're checking for the presence of the class that has the exact same values as the one we previously added, they're still separate instances and you'll end up with duplicates in your list.

An alternative in the very limited case would be to use a LINQ method to check whether the list already contains an entry with a property that can be compared, such as an int ID or something:

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

Again, if it's more than a one off, implement it the right way with IEquatable. See Microsoft's documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM