簡體   English   中英

在C#中搜索字符串數組列表的有效方法

[英]Efficient way to search List of String Arrays in C#

我有這樣的結構,

String[] variable1= new String["ABC", "FSS" , "FSFS", "GDGDDS"];
String[] variable2= new String["SA", "GS" , "QE", "HF"];


static List<String[]> allList = new List<String[]>();;

allList .Add(variable1);
allList .Add(variable2);

當提供一個String ,我想搜索allList並提供結果(如果找到了該數組)。

對以有效方式進行存檔有幫助嗎?

兩種提供的解決方案都是線性運行的,如果您有很多單詞並且進行很多查詢,這將太慢。

您可以使用字典。 字典在內部使用哈希表,它會快很多。

要將所有字符串放入字典中,可以執行以下操作:

Dictionary<String, String[]> dict = new Dictionary<String, String[]>();
foreach(String[] arr in allList)
    foreach(String str in arr)
        dict[str] = arr;

然后,您可以輕松地搜索它:

String s = "ABC";
if(dict.ContainsKey(s))
    // result is dict[s]
else
    // String is not in any array

希望能幫助到你!

您也可以嘗試

var output=allList.Where(x=>(string.Join(",", x)+",").IndexOf(input+",")!=-1)
                  .FirstOrDefault();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM