0

I want to store DateTime values in a data structure(either a HashSet or List).I later want to use that structure for comparison with some other DateTime values.

  1. I want to know the different in mechanism of how "==" and contains() works.
  2. Also I want to know the difference in mechanism with respect to HashSet and List types?
  3. I assume contains () in HashSet would be O(1) vs O(n) in List?
  4. What is more reliable to compare DateTime objects "==" or contains?
  5. Is LINQ faster or the same?

Code -

List<DateTime> list1 = new List<DateTime>();
HashSet<DateTime> list2 = new HashSet<DateTime>();

list1.Add(new DateTime(DateTime.Now.Date));
list2.Add(new DateTime(DateTime.Now.Date));

DateTime someOtherDate = DateTime.Now.Date;

if(list1.Contains(someOtherDate))
 //thendosomething
VS
if(list2.Contains(someOtherDate))
 //thendosomething


AND 

foreach(DateTime tmpValue in list1)
{
  if(tmpValue == someOtherDate)
   //thendosomehting
}

VS

foreach(DateTime tmpValue in list2)
{
  if(tmpValue == someOtherDate)
   //thendosomehting
}

All of the above VS -

var rows = from e in list1
           where e == someOtherDate
           select e
sandunes90
  • 455
  • 2
  • 4
  • 22

1 Answers1

1

I want to know the different in mechanism of how "==" and contains() works.

== is checking two objects/structs for equality. List.Contains and HashSet.Contains check if an object is contained within that list.

Also I want to know the difference in mechanism with respect to HashSet and List types?

HashSet is a hash table. List is an array that can grow.

I assume contains () in HashSet would be O(1) vs O(n) in List?

Yes

What is more reliable to compare DateTime objects "==" or contains?

If you are checking if two DateTime values are equal, use ==. If you are checking if a collection contains a specific DateTime, use Contains()

Your foreach loops through the List are exactly what List.Contains is doing (but not at all what HashSet.Contains does)

Finally, your Linq query is going to create a new IEnumerable<DateTime> under the table, that evaluates O(N) over the list

Tim
  • 5,940
  • 1
  • 12
  • 18
  • What is contains in hashset doing? – sandunes90 Mar 02 '17 at 07:51
  • It is doing a hashtable lookup O(1) to see if the value is there. It by far is the most performant way to handle checking if a value exists in a collection-- assuming the collection size is significant. If you only have 2 or 3 values in the collection, the List might be more performant – Tim Mar 02 '17 at 15:47