dev*_*ero 2 .net c# arrays string
我有一个包含很多路径的List.我有一个特定的路径,我想检查此列表,看看是否有任何路径使用此路径,即:
f.StartsWith(r.FILENAME) && f != r.FILENAME
Run Code Online (Sandbox Code Playgroud)
这样做的最快方法是什么?
编辑:完成以下答案的功能:
static bool ContainsFragment(string[] paths, string fragment)
{
// paths **must** be pre-sorted via Array.Sort(paths);
if (paths.Length == 0) return false;
int index = Array.BinarySearch(paths, fragment);
if (index >= 0 && index+1 < paths.Length)
{ //we found it
if (paths[index + 1].StartsWith(fragment) &&
paths[index + 1].EndsWith(".manifest"))
{
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
该最快的方法可能是用二进制搜索:
static bool ContainsFragment(string[] paths, string fragment)
{
// paths **must** be pre-sorted via Array.Sort(paths);
if (paths.Length == 0) return false;
int index = Array.BinarySearch(paths, fragment);
// we want the index of the *next highest* path
if (index < 0) { // no match
index = ~index;
} else { // exact match
index++; // for strict substring (non-equal)
}
return index < paths.Length && paths[index].StartsWith(fragment);
}
Run Code Online (Sandbox Code Playgroud)
但如果你只做了几次,那么对阵列进行分类的成本将超过任何好处; 在这种情况下,只需扫描数组 - 使用LINQ等,或只是:
bool found = false;
for(int i = 0 ; i < paths.Length ; i++) {
if(paths[i].StartsWith(fragment) &&
paths[i].Length != fragment.Length)
{
found = true;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1077 次 |
| 最近记录: |