【问题标题】:List of Subpath strings Compared to List of FileInfo子路径字符串列表与 FileInfo 列表相比
【发布时间】: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 编写高效的代码。

标签: c# compare


【解决方案1】:

Linq 是一个抽象级别,因此它永远不会比手动循环更快。

至于您的问题,我会尝试将_imageFilesInFolderPathList 转换为包含文件名的HashSet&lt;string&gt;。此外,您还需要比较使用 EndsWith 的整个字符串以提高性能。

【讨论】:

  • 我使用 EndsWith 的原因是因为我不知道路径字符串 (dr) 的长度,即它们不是完整路径。
猜你喜欢
  • 2023-03-04
  • 2013-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
相关资源
最近更新 更多