【发布时间】:2017-12-07 13:21:29
【问题描述】:
我有以下方法将子路径列表(行)与List<FileInfo> 进行比较,并将任何缺失的条目添加到列表_missingImageFolderEnteries。我正在使用 LINQ 并注意到它的处理速度似乎出奇的慢。关于如何提高性能的任何想法或想法?也许 LINQ 不适合这里,但我认为它应该比标准循环更有效。
private List<FileInfo> _imageFilesInFolderPathList = new List<FileInfo>();
private readonly List<Tuple<string, string>> _missingImageFolderEnteries = new List<Tuple<string, string>>();
private void CrossCheckImageWithFolder(EnumerableRowCollection<DataRow> Rows)
{
foreach (var dr in Rows)
{
var filepath = dr[ImagePathHeader].ToString();
if (!_imageFilesInFolderPathList.Any(row =>
row.FullName.EndsWith(FilePathHandler.FormatSubPath(filepath))))
_missingImageFolderEnteries.Add(
new Tuple<string, string>(
filepath.Substring(CommonInitFolder.Length).StartsWith("\\")
? filepath.Substring(CommonInitFolder.Length)
: "\\" + filepath.Substring(CommonInitFolder.Length),
" does not exist in image folder"));
}
_missingImageFolderEnteries.Sort((x, y) => y.Item1.CompareTo(x.Item1));
}
public static string FormatSubPath(string path, bool needsSlash = true)
{
var returnPath = path;
if (returnPath.StartsWith("."))
returnPath = returnPath.Substring(1);
if (!returnPath.StartsWith("\\") && needsSlash)
returnPath = "\\" + returnPath;
else if (returnPath.StartsWith("\\") && !needsSlash)
returnPath = returnPath.Substring(1);
return returnPath;
}
【问题讨论】:
-
" 我认为它应该比标准循环更有效" LINQ 只是隐藏了循环。实际上,使用 LINQ 编写低效代码比使用经典循环更容易。但是,如果您知道底层发生了什么,您也可以使用 LINQ 编写高效的代码。