我在我的程序中持有兩個列表 - 一個主列表和另一個不斷更新的臨時列表。每隔一段時間,臨時列表就會刷入主列表。構建HashSet時允許重複<T>與列表<T>參數?
主列表是HashSet(用於無重複),臨時列表是List(用於索引功能)。我通過調用
HashSet<T>.UnionWith(List<T>)
在我的測試沖洗後者向前,我發現,重複做他們的方式進入榜單,但我認爲這是不可能在一個HashSet。有人可以確認/糾正嗎?我一直無法在MSDN中找到它。
我在我的程序中持有兩個列表 - 一個主列表和另一個不斷更新的臨時列表。每隔一段時間,臨時列表就會刷入主列表。構建HashSet時允許重複<T>與列表<T>參數?
主列表是HashSet(用於無重複),臨時列表是List(用於索引功能)。我通過調用
HashSet<T>.UnionWith(List<T>)
在我的測試沖洗後者向前,我發現,重複做他們的方式進入榜單,但我認爲這是不可能在一個HashSet。有人可以確認/糾正嗎?我一直無法在MSDN中找到它。
列表(用於索引功能)。
你會想要一個索引字典。 關於這一點,雖然,這裏有一個非常簡單的程序,說明您的問題:
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;
}
}
它如果你的類型將覆蓋GetHashCode()
和Equals()
correctly不可能。我的猜測是你的類型沒有做到這一點。 (或者你的散列集已經與自定義相等比較,你想要什麼沒有做創建的。)
如果您認爲並非如此,請張貼代碼:)
但是,是的,它真的將正常使用時防止重複。
我很欣賞這個例子:)我將在我的類中覆蓋這兩個函數,我希望能解決這個問題。 – blizz