C# 二维列表中的二进制搜索

C# 二维列表中的二进制搜索,c#,C#,我有一个维度列表: 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

我有一个维度列表:

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

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

在这种情况下,您需要提供自己的客户IComparer实现comparator

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]);
    }
公共类比较器:IComparer
{
公共整数比较(IList x,IList y)
{
//将比较结果基于相应列表中的第一个元素
//基本上
返回x[0]。比较到(y[0]);
}
您可以这样称呼它,提供一个列表,其中只填写您正在搜索的字段

int row = index_en_bg.BinarySearch(new List<string>() {searchingstr},new Comparer());
int row=index_en_bg.BinarySearch(new List(){searchingstr},new Comparer());

据我所知,您应该改用
字典
,方法如下:

// 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"];
//1创建字典
var dic=新字典();
dic[“word1”]=“translation1”;
dic[“word2”]=“translation2”;
dic[“word3”]=“translation3”;
//2寻找翻译
var trans=dic[“字1”];
而且
字典
真的很好用


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

因为您总是使用列表的第一项进行搜索,所以您也可以使用字典

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

正如前面所回答的,它的性能比列表要好得多。

投票支持第一个问题!欢迎:)你介意解释一下你为什么不想用字典吗?@Patrick我的英语不太好,很难为我解释,抱歉,但OP说他不想用字典……这很令人费解,但也是他的一部分要求。是的,它是我也很困惑,所以我添加了IComparer选项。这不应该是
IComparer
?我这样做:
公共类MyBinComparer:IComparer>{public int Compare(列表x,列表y){StringComparer comparer1=StringComparer.OrdinalIgnoreCase;返回comparer1.Compare(x[0],y[0]);}
int row=index_en_bg.BinarySearch(new List(){searkingstr},new MyBinComparer());
但是它不能正常工作,BinarySearch返回的总是比索引中最后一项大的整数_bg@vinsa您确定索引\u en\u bg中的项目排序正确吗?即,按每个包含列表的第一个元素的字母顺序排列?b因为如果不是,您就不能执行二进制搜索。@vinsa,现在应该很清楚了不使用字典会让你陷入各种困境——也许你应该解释为什么字典不适合你,因为它自然适合你的问题。@fvu因为我必须使用BinSearch,即使你写了一个单词的一部分,它也能找到翻译,DictionAnry[关键字]如果您只写一个单词的一部分,将返回null。如果您写ca或cat,BinSearch将重新返回cat,但DictionAnry['ca']将返回null。是的,列表已排序。在stackoverflow上,如果您同意,您通常会留下评论或向上投票,而不是编写新答案。由于您只有1个代表点,您还不能留下评论,但您可以向上投票您喜欢的答案。
    var d = Dictionary<string, List<string>>();