7

在遍历表时,我将一堆所谓的唯一项目 ID 作为键存储,并将文件位置作为哈希表中的值存储。当我运行它时,我需要确保它们的键/位置对是唯一的或抛出错误消息。我已经设置了哈希表并正在加载值,但不确定要测试什么:

Hashtable check_for_duplicates = new HashTable();
foreach (object item in items)
{
    if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
        //what goes here?  Would be contains item["Path"] as the value for the key)
    {
        //throw error
    }
}
4

8 回答 8

11

试试这个:

Hashtable check_for_duplicates = new HashTable();
foreach (object item in items)
{
    if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
        check_for_duplicates[item["ItemID"]].Equals(item["Path"]))
    {
        //throw error
    }
}

此外,如果您使用的是 .NET 2.0 或更高版本,请考虑使用泛型,如下所示:

List<Item> items; // Filled somewhere else

// Filters out duplicates, but won't throw an error like you want.
HashSet<Item> dupeCheck = new HashSet<Item>(items); 

items = dupeCheck.ToList();

实际上,我刚刚检查过,看起来 HashSet 只是 .NET 3.5。字典更适合 2.0:

Dictionary<int, string> dupeCheck = new Dictionary<int, string>();

foreach(Item item in items) {
    if(dupeCheck.ContainsKey(item.ItemID) && 
       dupeCheck[item.ItemID].Equals(item.Path)) {
        // throw error
    }
    else {
        dupeCheck[item.ItemID] = item.Path;
    }    
}
于 2009-03-19T17:30:08.743 回答
4

如果您Dictionary改用该方法,则该TryGetValue方法会有所帮助。我不认为对于几乎不推荐使用的Hashtable类有更好的方法。

object value;
if (dic.TryGetValue("key", out value) && value == thisValue)
  // found duplicate
于 2009-03-19T17:29:06.297 回答
3
if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
    check_for_duplicates[item["ItemID"]] == item["Path"])
{
    //throw error
}
于 2009-03-19T17:29:46.827 回答
3

ContainsKey 是最好的方法。

如果您不被迫使用 .NET 1.1,我会使用 .NET 2.0 中引入的 Dictionary。

从性能上看,它比 Hashtable 好得多,并且是强类型的。

Dictionary<string, int> betterThanAHash = new Dictionary<string, int>();

betterThanAHash.ContainsKey("MyKey");
于 2009-03-19T17:32:12.360 回答
2
Hashtable check_for_duplicates = new HashTable();

foreach (object item in items) 
{
    if (check_for_duplicates.ContainsKey(item["ItemID"]) && check_for_duplicates[item["ItemID"]] == item["Path"])
    {
        //throw error
    } 
}

我相信这就是你要找的。

编辑 - 看起来我被打败了:P

于 2009-03-19T17:34:56.953 回答
2

为什么不使用 aDictionary代替?

如果您尝试Add使用已存在于Dictionary.

这样,您可以在添加副本时立即捕获副本,而不是check_for_duplicates稍后执行测试。

于 2009-03-19T18:23:56.103 回答
1

这有点取决于 items 数组是什么......你会想要这样的东西:

check_for_duplicates.ContainsValue(item["Path"]);

假设该项目是某种形式的查找。确实,您需要强制转换项目,或使用类型系统通过索引实际访问任何值。

于 2009-03-19T17:31:28.710 回答
1

你没有说你使用的是什么版本的东西。您是否有理由必须使用 Hashtable 与 HashSet?如果您的数据结构不允许重复,则无需检查重复项。也可以看看:

http://www.vcskicks.com/csharp_data_structures2.html

除此之外,这里已经回答了如何在 Hashtable 中完成同样的事情的问题。我只是指出,如果你一开始就禁止,你就不需要做所有的病理检查。

于 2009-04-17T17:51:19.527 回答