kmx*_*llo 5 c# linq ienumerable fileinfo
我有以下代码,我收到"if语句"错误说FileInfo不包含定义"包含"
查看文件是否在目录中的哪个是最佳解决方案?
谢谢
string filePath = @"C:\Users\";
DirectoryInfo folderRoot = new DirectoryInfo(filePath);
FileInfo[] fileList = folderRoot.GetFiles();
IEnumerable<FileInfo> result = from file in fileList where file.Name == "test.txt" select file;
if (fileList.Contains(result))
{
//dosomething
}
Run Code Online (Sandbox Code Playgroud)
Gra*_*ICA 15
删除fileList.Contains(result)并使用:
if (result.Any())
{
}
Run Code Online (Sandbox Code Playgroud)
.Any()是一个LINQ关键字,用于确定结果中是否包含任何项目.有点像做一个.Count() > 0,除了更快.使用.Any(),只要找到一个元素,就不再枚举序列,结果就是True.
实际上,您可以将代码的最后五行从from file in...底部删除,替换为:
if (fileList.Any(x => x.Name == "test.txt"))
{
}
Run Code Online (Sandbox Code Playgroud)