将字符串与C#2.0中的字符串数组进行比较的最快方法

在C#2.0中将字符串与字符串数组进行比较的最快方法是什么

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

你想要什么样的比较? 你想知道给定的字符串是否在数组中?

 bool targetStringInArray = array.Contains(targetString); 

你想要一组比较值(正数,负数,零)?

 var comparisons = array.Select(x => targetString.CompareTo(x)); 

如果您正在检查包含(即第一个选项)并且您要使用多个字符串执行此操作,那么从数组中构建HashSet可能会更好:

 var stringSet = new HashSet(array); if (stringSet.Contains(firstString)) ... if (stringSet.Contains(secondString)) ... if (stringSet.Contains(thirdString)) ... if (stringSet.Contains(fourthString)) ... 

如果您使用单个数组执行此操作多次,则应对数组进行排序并对其进行二进制搜索:

 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; 

//从源列表中获取数据清单checklist = Directory.GetFiles(SourcePath,“ ”,SearchOption.AllDirectories).Where(x => x.ToLower()。EndsWith(“apk”))。ToList();

  //get date from a text file List 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); } }