在二维列表中搜索BinarySearch

本文关键字:列表 搜索 BinarySearch 二维 | 更新日期: 2023-09-27 18:15:36

我有尺寸列表:

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 });

我会根据第一列(words)进行二分搜索,如下所示:

int row = index_en_bg.BinarySearch(searchingstr);

,但它只适用于一维列表。在我的例子中,我如何将它扩展到二维列表呢?我不想使用Dictionary

在二维列表中搜索BinarySearch

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

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());

就我所知,你应该使用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>>并将其传递给函数。

当您总是使用列表的第一项进行搜索时,您也可以使用字典。

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

如前所述,它比List要好得多。