how to check if object already exists in a list

前端 未结 9 1783
梦谈多话
梦谈多话 2020-11-28 05:41

I have a list

  List myList

and I am adding items to a list and I want to check if that object is already in the list.

9条回答
  •  北海茫月
    2020-11-28 05:51

    Are you sure you need a list in this case? If you are populating the list with many items, performance will suffer with myList.Contains or myList.Any; the run-time will be quadratic. You might want to consider using a better data structure. For example,

     public class MyClass
        {
            public string Property1 { get; set; }
            public string Property2 { get; set; }
    
        }
    
        public class MyClassComparer : EqualityComparer
        {
            public override bool Equals(MyClass x, MyClass y)
            {
                if(x == null || y == null)
                   return x == y;
    
                return x.Property1 == y.Property1 && x.Property2 == y.Property2;
            }
    
            public override int GetHashCode(MyClass obj)
            {
                return obj == null ? 0 : (obj.Property1.GetHashCode() ^ obj.Property2.GetHashCode());
            }
        }
    

    You could use a HashSet in the following manner:

      var set = new HashSet(new MyClassComparer());
      foreach(var myClass in ...)
         set.Add(myClass);
    

    Of course, if this definition of equality for MyClass is 'universal', you needn't write an IEqualityComparer implementation; you could just override GetHashCode and Equals in the class itself.

提交回复
热议问题