2013-12-13 39 views
4

我使用C#語言,我對List<Tuple<int,int>>有一些疑問。假設我創建了一個List<Tuple<int,int>>然後插入一些條目,將其想:(12,3),(154,43),(85,342)在c#中的列表<Tuple <int,int>>中的二進制搜索#

現在我想只是第一個項目,即僅僅通過item1搜索List,我想通過二進制搜索做到這一點。

是這樣的:

List<Tuple<int,int>> tt = new List<Tuple<int,int>>(); 
tt.Add(new Tuple<int,int>(12,32)); 
tt.sort(); 
tt.binarysearch(item1:12); 

和一些輸出是這樣的:

12 32

現在有沒有什麼解決辦法嗎?

回答

6

是的,二分查找需要的IComparer,你可以創建一個IComparer<Tuple<int, int>>

因此繼承了自己的自定義比較:

public class BinarySearchComparer : IComparer<Tuple<int, int>> 
{ 
    public int Compare(Tuple<int, int> f1, Tuple<int, int> f2) 
    { 
     return Comparer<int>.Default.Compare(f1.Item1, f2.Item1); 
    } 
} 

和示例:

tt.Binarysearch(12, new BinarySearchComparer()); 

查看更多信息:http://msdn.microsoft.com/en-us/library/ftfdbfx6(v=vs.110).aspx

+0

嘿Erti-Chris!非常感謝,你做到了! – Chavoosh

+0

這段代碼是可執行的還是隻是一個示例? – Chavoosh

+0

是的,它應該工作。我之前做過一些編輯,也許你沒有刷新過? –

相關問題