2013-08-19 176 views
0

我有兩個SortedSets:SortedSet.Contains給出錯誤「至少一個對象必須實現ICombarable」

SortedSet<SortedSet<int>> sset1 = new SortedSet<SortedSet<int>>(); 
SortedSet<SortedSet<int>> sset2 = new SortedSet<SortedSet<int>>(); 

後來我檢查我提出一個新的有序集合:

SortedSet<int> newSset = MethodThatReturnsSortedSet(); 

現在我想檢查sset1和sset2包含newSset:

if (!sset1.Contains(newSset) && !sset2.Contains(newSset)) <--error on this line 
    { 
     sset1.Add(next); 
     //some more code 
    } 

所以我得到的錯誤是參數異常,「其中至少一個對象必須實現IComparable。

我已經看過其他同樣問題的問題,但在他們的情況下,他們想要比較自己的類。我只是檢查某個項目是否在一個集合中。所以是啊..我不知道如何解決這個問題,任何指針?

+0

爲什麼使用SortedSet的SortedSet?另一個集合是否也會像其內容那樣需要IComparable? – FrankPl

+0

我想我可以將它們改爲Hashset – Aelion

回答

0

你不能有SortedSetSortedSet A S,除非您指定一個自定義比較,因爲SortedSet本身並不實現IComparable

每當你使用類型SortedSet<X>,一組是基於X增加順序排列,所以X必須IComparable<X>或只是IComparable,否則SortedSet<X>必須與構造函數重載,它允許你給一個自定義對象被創建類型IComparer<X>

這兩個SortedSet<int>的至上:

{ 3, 8, 25, } 

或:

{ 3, 7, 9, 58, 12345678, } 

此外:在沒有答案的上方,我假設你想要的字典比較,這似乎有些不自然。我寫了這個類:

​​

那類從Comparer<>類繼承並實現正因爲如此IComparer<>接口。您在構建「嵌套」SortedSet時使用它,例如:

LexicographicComparer lc = new LexicographicComparer(); 
SortedSet<SortedSet<int>> sset1 = new SortedSet<SortedSet<int>>(lc); 
SortedSet<SortedSet<int>> sset2 = new SortedSet<SortedSet<int>>(lc); 
相關問題