C# 中 HashSet 和 List 与日期时间值的 contains() 和相等运算符之间的区别?



我想将DateTime值存储在数据结构(HashSet或List)中。稍后,我想使用该结构与其他一些日期时间值进行比较。

  1. 我想知道"=="和contains()如何工作的不同机制。
  2. 我还想知道哈希集和列表类型的机制差异?
  3. 我假设哈希集中的包含 () 将是列表中的 O(1) 与 O(n)?
  4. 比较日期时间对象"=="或包含什么更可靠?
  5. LINQ 是更快还是相同?

法典-

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
}

以上所有 VS -

var rows = from e in list1
where e == someOtherDate
select e

我想知道"=="和contains()机制的不同 工程。

==正在检查两个对象/结构的相等性。List.ContainsHashSet.Contains检查对象是否包含在该列表中。

我还想知道机制的差异 哈希集和列表类型?

HashSet是一个哈希表。List是一个可以增长的数组。

我假设哈希集中的包含 () 将是列表中的 O(1) 与 O(n)?

是的

比较日期时间对象"=="或包含什么更可靠?

如果要检查两个DateTime值是否相等,请使用==。 如果要检查集合是否包含特定DateTime,请使用Contains()

您在列表中循环foreach正是List.Contains正在做的事情(但根本不是HashSet.Contains所做的)

最后,Linq 查询将在表下创建一个新IEnumerable<DateTime>,用于计算列表上的 O(N)

最新更新