【问题标题】:Find missing element in in dictionary from relative hashset [duplicate]从相对哈希集中查找字典中的缺失元素[重复]
【发布时间】:2014-10-15 20:37:31
【问题描述】:

我是 C# 的初学者。我的情况是我有一本字典

var enteries = new Dictionary<int, Entry>();

我正在迭代它

foreach (KeyValuePair<int, Entry> entry in enteries)

我有一个hashset&lt;int&gt;,它包含所有的键,如 1、2、3。有时字典缺少一个键,我怎么知道我在字典中迭代的当前键是否从哈希集中丢失?

基本上我正在尝试编写 CVS 文件,我需要知道是否缺少密钥,以便我可以为该 id 写一些空行。 我也想整理东西..

好像有误会:

Suppose enteries have keys, 238, 260 
hashset has 238,260,250 

当我遍历字典中的每个键对时,我将如何关联缺少一个元素,即 250,例如,我应该输出一些东西。

【问题讨论】:

  • 检查yourHashSet.Contains(entry.Key)?
  • @cdhowie 你能看到编辑吗?
  • @andre 我明白了。我的回答适用于这种情况。

标签: c# c#-3.0


【解决方案1】:

最简单的代码不会是最有效的,但会起作用;将一组键合并在一起,然后迭代:

foreach (int key in enteries.Keys.Union(yourHashSet)) {
    Entry entry;
    if (enteries.TryGetValue(key, out entry)) {
        // The key is in the dictionary; the entry variable contains the value.
    } else {
        // The key is not in the dictionary.
    }
}

如果要对键进行排序,只需在并集之后应用此操作即可:

foreach (int key in enteries.Keys.Union(yourHashSet).OrderBy(i => i)) {

【讨论】:

    【解决方案2】:

    我怎么知道我正在迭代的当前键是否在 哈希集中缺少字典?

    假设您有一个HashSet&lt;int&gt; hashSet 实例,您可以使用Contains 方法来确定此哈希集中是否包含一个整数值并采取相应措施:

    HashSet<int> hashSet = ...
    
    foreach (KeyValuePair<int, Entry> entry in enteries)
    {
        if (hashSet.Contains(entry.Key))
        {
            // The current key is contained within the hashSet
        }
        else 
        {
            // The current key is not contained within the hashSet
        }
    }
    

    【讨论】:

    • 我需要反向操作。哈希集包含所有应该存在的键,但字典可能缺少哈希集中的键。
    • 然后使用当前键简单地循环遍历哈希集的键和字典上的TryGetValue
    【解决方案3】:

    改变你的观点。 据我了解,您的 HashSet 是每个需要的密钥。所以遍历 HashSet 并找到 Dictionary 中每个 HashSet-Entry 的键。

    【讨论】:

    • 你找到我了,你能详细说明一些代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2014-12-18
    • 2021-04-03
    • 2014-03-26
    相关资源
    最近更新 更多