【问题标题】:The fastest way to find dictionary keys that are not exist in another list [closed]查找另一个列表中不存在的字典键的最快方法[关闭]
【发布时间】:2019-08-07 11:10:05
【问题描述】:

我有一本字典 A,我想以快速且适当的方式找到 B 中未列出的 int 键。

Dictionary<int,object> A;

List<int> B;

我想要得到

A KEYS ARE NOT EXISTING IN B

有没有一种快速而优雅的方法?

【问题讨论】:

  • 好键是一个列表..你试过什么?
  • 你想对 B 中不存在的键做什么?你将它们输出到控制台吗?
  • 我很震惊为什么这个问题被否决了。我的问题很明确。
  • 你可以像A.Keys.Except(B)一样使用Linq
  • @dymanoid 请告诉我们为什么这个问题太板了?

标签: c# .net linq dictionary


【解决方案1】:

您可以尝试使用System.Linq 中的Except 方法

var result = A.Keys.Except(B);

【讨论】:

  • B 是列表?
  • 是的,根据你的问题:)
  • 我会试试的。
  • 很好的解决方案。谢谢
【解决方案2】:

您可以创建一个new HashSet&lt;int&gt; (A.Keys),并使用Hashset 的ExceptWith() 方法。

编辑: 既然您认为散列会破坏性能,这是一个示例代码,您可以将其放入 linqpad。在大多数情况下,这仍然比仅使用 LINQ .Except()快 30% 左右

Dictionary<int, int> A = new Dictionary<int, int>();
List<int> B = new List<int>();

// test filling...
Random r = new Random();
for (int i = 0; i < 1000000; i++)
{
    int rnd = r.Next(0, 2000000);
    A[rnd] = rnd;

    rnd = r.Next(0, 2000000);
    B.Add(rnd);
}

// Get time for LINQ Except
Stopwatch w = Stopwatch.StartNew();
var count = A.Keys.Except(B).Count();
w.Stop();
w.Dump();
count.Dump("Count");

// Get time for Hashset
w = Stopwatch.StartNew();

HashSet<int> ha = new HashSet<int>(A.Keys);
ha.ExceptWith(B);
count = ha.Count;

w.Stop();
w.Dump();
count.Dump("Count");

【讨论】:

  • 散列会浪费时间。
  • int.GetHashCode() 只是返回 int,所以哈希会很快。
  • 好主意和解决方案。
  • @Mr.AF Except of linq 正在使用 ExceptIterator,它使用一个集合来检查值。这是排除值的最快平均方法。如果您确定排除值列表非常小,则迭代它们可能会更快 - 但您需要一个循环来迭代与哈希码计算。
猜你喜欢
  • 2016-02-11
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 2010-11-21
  • 1970-01-01
  • 2015-08-05
相关资源
最近更新 更多