在C#2.0中,比较一个字符串和一个字符串数组的最快方法是什么?

18

在C#2.0中,比较一个字符串与一个字符串数组的最快方式是什么?

5个回答

32

您需要什么类型的比较?您想知道给定字符串是否在数组中吗?

bool targetStringInArray = array.Contains(targetString);
你是否需要一个比较值的数组(包括正数、负数和零)?
var comparisons = array.Select(x => targetString.CompareTo(x));

如果你要检查是否包含某个字符串(即第一个选项),并且你将使用多个字符串进行此操作,那么最好从数组构建一个HashSet<string>

var stringSet = new HashSet<string>(array);

if (stringSet.Contains(firstString))  ...
if (stringSet.Contains(secondString)) ...
if (stringSet.Contains(thirdString))  ...
if (stringSet.Contains(fourthString)) ...

9

你的意思是要查看字符串是否在数组中吗?我记不清数组是否支持.Contains()方法,如果不支持,可以创建一个List<string>,通过AddRange()将数组添加到列表中,然后调用list.Contains({要比较的字符串})。将返回一个布尔值,指示字符串是否在数组中。


1
在2.0中,您需要执行(new List<String>(array)).Contains(targetString); - 但从3.5开始,您可以使用IEnumerable<String>.Contains扩展方法,因此它也适用于数组。 - vgru
1
在2.0中,您可以使用简单的Array.IndexOf(arr, val) >= 0来检查数组是否包含特定值。 - Mehrdad Afshari

5
如果您需要对同一个数组进行多次操作,建议先对该数组进行排序,再使用二分查找算法:
Array.Sort(array);
int index = Array.BinarySearch(array, input);
// if (index < 0) 
//      does not exists, "items > ~index" are larger and "< ~index" are smaller
// otherwise, "items > index" are larger and "< index" are smaller.

否则,就朴素地检查整个数组:
bool exists = Array.IndexOf(array, input) >= 0;

1
如果你要做很多次,比起二分查找(假设它相当大),有更高效的搜索方法。我会选择基于哈希的东西,例如 HashSet。 - Jon Skeet
1
没错,哈希表/二叉搜索树之争...总之两者都比搜索整个数组要好。HashSet只在3.5中可用。 - Mehrdad Afshari

0
如果您要验证一个列表是否是另一个列表的一部分,那么可以使用Contains()方法。
比如说,
List<string> list1 = new List<string>(){"1", "2"};
List<string> list2 = new List<string>(){"1", "2", "3"};

list2.Contains(list1) //will be True, but not vice versa.

话虽如此,如果你想要精确匹配而非部分匹配,你可以使用Except()函数,并检查余下的部分。

if(list2.Except(list1).Length == 0) //will return false.

-1
//从源中获取列表中的数据 List checklist = Directory.GetFiles(SourcePath, ".", SearchOption.AllDirectories).Where(x => x.ToLower().EndsWith("apk")).ToList();
            //get date from a text file
           List<string>  ls = ReadFile();

            foreach(string file in checklist)
            {
                //get file name
                string filename = Path.GetFileName(file);

                string TargetLocation = Path.Combine(TargetPath, filename);

                //now compare single string to a list 
                //it give in true and false 
                if(ls.Contains(filename)) 
                {
                    //do your task
                    //File.Copy(file, TargetLocation);
                }
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接