使用Enumerable.Any
擴展方法,當擴展方法返回true
當且僅當序列中存在給定謂詞返回true
的某個項目時。
string search = "foldername/file.txt";
bool result = X.Any(s => search.StartsWith(s));
當然,StartsWith
可能實際上並不適合您的情況。如果X
中只有一個名爲foldername2
的文件夾會怎麼樣?在這種情況下,你不希望result
爲true
,我懷疑。
如果你想在X
搜索匹配的項目,你可以做到以下幾點。
string search = "foldername/file.txt";
IEnumerable<string> result = X.Where(s => search.StartsWith(s));
如果你想在X
,搜索匹配的第一個項目,你可以做到以下幾點。
List<string> X = new List<string>(){
"launch.txt","reset.txt","foldername","otherfoldername"
};
string search = "foldername/file.tx";
var searchInfo = new
{
FileNameWoe = Path.GetFileNameWithoutExtension(search),
FileName = Path.GetFileName(search),
Directory = Path.GetDirectoryName(search)
};
IEnumerable<String> matches = X.Select(x => new
{
str = x,
FileNameWoe = Path.GetFileNameWithoutExtension(x),
FileName = Path.GetFileName(x),
Directory = Path.GetDirectoryName(x)
}).Where(xInfo => searchInfo.FileName == xInfo.FileNameWoe
|| searchInfo.FileNameWoe == xInfo.FileName
|| searchInfo.Directory == xInfo.Directory
|| searchInfo.Directory == xInfo.FileNameWoe
|| searchInfo.FileNameWoe == xInfo.Directory)
.Select(xInfo => xInfo.str)
.ToList();
發現:foldername
,因爲一個文件名的FileNameWithoutExtension
等於您要搜索的路徑的目錄
string search = "foldername/file.txt";
string result = X.FirstOrDefault(s => search.StartsWith(s));
與論壇網站不同,我們不使用「謝謝」或「任何幫助表示讚賞」,或在[so]上簽名。請參閱「[應該'嗨','謝謝',標語和致敬從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be此外,FYI的術語是「預先感謝」,而不是「先進的感謝」。 –
很快就會發布 - 是的,這是正確的做法 –