2013-08-02 31 views
2

我在我的程序中持有两个列表 - 一个主列表和另一个不断更新的临时列表。每隔一段时间,临时列表就会刷入主列表。构建HashSet时允许重复<T>与列表<T>参数?

主列表是HashSet(用于无重复),临时列表是List(用于索引功能)。我通过调用

HashSet<T>.UnionWith(List<T>) 

在我的测试冲洗后者向前,我发现,重复做他们的方式进入榜单,但我认为这是不可能在一个HashSet。有人可以确认/纠正吗?我一直无法在MSDN中找到它。

回答

1

列表(用于索引功能)。

你会想要一个索引字典。 关于这一点,虽然,这里有一个非常简单的程序,说明您的问题:

class Program 
{ 
    static void Main(string[] args) 
    { 
     int totalCats = 0; 
     HashSet<Cat> allCats = new HashSet<Cat>(); 
     List<Cat> tempCats = new List<Cat>(); 

     //put 10 cats in 
     for (int i = 0; i < 10; i++) 
     { 
      tempCats.Add(new Cat(i)); 
      totalCats += 1; 
     } 

     //add the cats to the final hashset & empty the temp list 
     allCats.UnionWith(tempCats); 
     tempCats = new List<Cat>(); 

     //create 10 identical cats 
     for (int i = 0; i < 10; i++) 
     { 
      tempCats.Add(new Cat(i)); 
      totalCats += 1; 
     } 

     //join them again 
     allCats.UnionWith(tempCats); 
     //print the result 
     Console.WriteLine("Total cats: " + totalCats); 
     foreach (Cat curCat in allCats) 
     { 
      Console.WriteLine(curCat.CatNumber); 
     } 
    } 
} 

public class Cat 
{ 
    public int CatNumber { get; set; } 
    public Cat(int catNum) 
    { 
     CatNumber = catNum; 
    } 
} 

你的问题是,你不重写GetHashCode()方法和equals()。你需要两个哈希集保持独特。

这将工作,但GetHashCode()函数应该更健壮。我建议阅读.NET是如何做到这一点的:

class Program 
{ 
    static void Main(string[] args) 
    { 
     int totalCats = 0; 
     HashSet<Cat> allCats = new HashSet<Cat>(); 
     List<Cat> tempCats = new List<Cat>(); 

     //put 10 cats in 
     for (int i = 0; i < 10; i++) 
     { 
      tempCats.Add(new Cat(i)); 
      totalCats += 1; 
     } 

     //add the cats to the final hashset & empty the temp list 
     allCats.UnionWith(tempCats); 
     tempCats = new List<Cat>(); 

     //create 10 identical cats 
     for (int i = 0; i < 10; i++) 
     { 
      tempCats.Add(new Cat(i)); 
      totalCats += 1; 
     } 

     //join them again 
     allCats.UnionWith(tempCats); 
     //print the result 
     Console.WriteLine("Total cats: " + totalCats); 
     foreach (Cat curCat in allCats) 
     { 
      Console.WriteLine(curCat.CatNumber); 
     } 
     Console.ReadKey(); 
    } 
} 

public class Cat 
{ 
    public int CatNumber { get; set; } 
    public Cat(int catNum) 
    { 
     CatNumber = catNum; 
    } 

    public override int GetHashCode() 
    { 
     return CatNumber; 
    } 

    public override bool Equals(object obj) 
    { 
     if (obj is Cat) 
     { 
      return ((Cat)obj).CatNumber == CatNumber; 
     } 
     return false; 
    } 
} 
+0

我很欣赏这个例子:)我将在我的类中覆盖这两个函数,我希望能解决这个问题。 – blizz

7

如果你的类型将覆盖GetHashCode()Equals()correctly可能。我的猜测是你的类型没有做到这一点。 (或者你的散列集已经与自定义相等比较,你想要什么没有做创建的。)

如果您认为并非如此,请张贴代码:)

但是,是的,它真的正常使用时防止重复。

相关问题