5

我有维度列表:

List<List<string>> index_en_bg = new List<List<string>>();

   index_en_bg.Add(new List<string>() { word1, translation1 }); 
   index_en_bg.Add(new List<string>() { word2, translation2 }); 
   index_en_bg.Add(new List<string>() { word3, translation3 });

我会按第一列(单词)进行二进制搜索,如下所示:

int row = index_en_bg.BinarySearch(searchingstr);

但它仅适用于一维列表。在我的情况下,我将如何将其扩展为适用于二维列表?我不想使用Dictionary类。

4

3 回答 3

7

在这种情况下您需要提供您自己的客户 IComparer-实现比较器

public class Comparer: IComparer<IList<string>>
{
    public int Compare(IList<string> x, IList<string> y)
    {
        // base the comparison result on the first element in the respective lists
        // eg basically
        return x[0].CompareTo(y[0]);
    }

你会这样称呼它,提供一个列表,其中只填写你正在搜索的字段。

int row = index_en_bg.BinarySearch(new List<string>() {searchingstr},new Comparer());
于 2013-05-28T10:42:16.077 回答
2

好吧,据我了解,您应该改用Dictionary<K,V>这种方式:

// 1 creating the dictionary
var dic = new Dictionary<string, string>();
dic["word1"] = "translation1";
dic["word2"] = "translation2";
dic["word3"] = "translation3";

// 2 finding a translation
var trans = dic["word1"];

并且Dictionary<K,V>非常高效。

但是如果你坚持使用BinarySearch,你可以实现IComparer<List<string>>并将其传递给函数。

于 2013-05-28T10:43:54.460 回答
-1

由于您总是使用列表的第一项进行搜索,因此您也可以使用字典。

    var d = Dictionary<string, List<string>>();

如前所述,它的预制件比 List 好得多。

于 2013-05-28T10:53:17.793 回答