简体   繁体   English

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

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

I have Structure like this, 我有这样的结构,

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

When a String is provided i want to search allList and provide the result which array if were it found . 当提供一个String ,我想搜索allList并提供结果(如果找到了该数组)。

Any help archiving this in a Efficient way? 对以有效方式进行存档有帮助吗?

Both provided solutions run in linear time, which will be way too slow if you have lots of words and make lots of queries. 两种提供的解决方案都是线性运行的,如果您有很多单词并且进行很多查询,这将太慢。

You can use a Dictionary. 您可以使用字典。 A Dictionary uses a hash table internally and it will be much, much faster. 字典在内部使用哈希表,它会快很多。

To put all the strings in a dictionary, you can do: 要将所有字符串放入字典中,可以执行以下操作:

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

And then you can easily search it: 然后,您可以轻松地搜索它:

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

Hope it helps! 希望能帮助到你!

You can also try this 您也可以尝试

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